阅读量:2
在CentOS系统中使用C++进行日志记录,可以采用多种方法。以下是一些常用的日志库和示例代码:
1. 使用 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
2. 使用 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
#include
#include
#include
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
3. 使用标准库 iostream
如果你不想使用第三方库,可以使用C++标准库中的 iostream 进行简单的日志记录。
示例代码
#include
#include
#include
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++进行日志记录的方法。你可以根据自己的需求选择合适的日志库。
以上就是关于“CentOS C++如何进行日志记录”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm