在CentOS系統中使用C++進行日志記錄,可以采用多種方法。以下是一些常用的日志庫和示例代碼:
spdlog
庫spdlog
是一個非常流行且高效的C++日志庫。
spdlog
你可以通過包管理器安裝 spdlog
:
sudo yum install spdlog-devel
#include "spdlog/spdlog.h"
#include "spdlog/sinks/stdout_color_sinks.h"
int main() {
// 創建一個控制臺日志記錄器
auto console = spdlog::stdout_color_mt("console");
// 記錄不同級別的日志
console->info("Welcome to spdlog!");
console->warn("Some warning message");
console->error("Some error message");
return 0;
}
g++ -std=c++11 -o log_example log_example.cpp -lspdlog
./log_example
log4cpp
庫log4cpp
是另一個流行的C++日志庫,提供了豐富的功能。
log4cpp
你可以通過源碼編譯安裝 log4cpp
:
wget http://archive.apache.org/dist/logging/log4cpp/log4cpp-0.9.9.tar.gz
tar xvf log4cpp-0.9.9.tar.gz
cd log4cpp-0.9.9
mkdir build && cd build
cmake ..
make
sudo make install
#include <log4cpp/Category.hh>
#include <log4cpp/FileAppender.hh>
#include <log4cpp/OstreamAppender.hh>
#include <log4cpp/Priority.hh>
int main() {
// 創建一個文件日志記錄器
log4cpp::Appender* appender = new log4cpp::FileAppender("default", "example.log");
appender->setLayout(new log4cpp::PatternLayout());
appender->getLayout()->setConversionPattern("%d [%p] %m%n");
log4cpp::Category& root = log4cpp::Category::getRoot();
root.addAppender(appender);
root.setPriority(log4cpp::Priority::INFO);
// 記錄不同級別的日志
root.info("Welcome to log4cpp!");
root.warn("Some warning message");
root.error("Some error message");
delete appender;
return 0;
}
g++ -std=c++11 -o log4cpp_example log4cpp_example.cpp -llog4cpp
./log4cpp_example
iostream
如果你不想使用第三方庫,可以使用C++標準庫中的 iostream
進行簡單的日志記錄。
#include <iostream>
#include <fstream>
#include <ctime>
void logMessage(const std::string& message, const std::string& filename = "log.txt") {
std::ofstream logFile(filename, std::ios::app);
if (logFile.is_open()) {
time_t now = time(0);
char* dt = ctime(&now);
logFile << "[" << dt << "] " << message << std::endl;
logFile.close();
} else {
std::cerr << "Unable to open log file." << std::endl;
}
}
int main() {
logMessage("Welcome to standard logging!");
logMessage("Some warning message");
logMessage("Some error message");
return 0;
}
g++ -std=c++11 -o std_log_example std_log_example.cpp
./std_log_example
以上是幾種在CentOS系統中使用C++進行日志記錄的方法。你可以根據自己的需求選擇合適的日志庫。