温馨提示×

Linux系统C++如何做日志

小樊
58
2025-08-14 02:57:33
栏目: 编程语言

在Linux系统中使用C++进行日志记录,可以采用多种方法。以下是一些常用的方法和库:

1. 使用标准库 <iostream> 和文件流 <fstream>

这是最简单的方法,直接将日志信息输出到文件中。

#include <iostream> #include <fstream> #include <string> #include <ctime> void logMessage(const std::string& message) { std::ofstream logFile("app.log", 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("This is a log message."); return 0; } 

2. 使用第三方日志库

有许多成熟的第三方日志库可以使用,例如 spdloglog4cppglog 等。这些库提供了更多的功能和更好的性能。

使用 spdlog

spdlog 是一个非常流行且高效的C++日志库。

首先,安装 spdlog

sudo apt-get install libspdlog-dev 

然后,在你的C++代码中使用它:

#include "spdlog/spdlog.h" #include "spdlog/sinks/basic_file_sink.h" int main() { auto logger = spdlog::basic_logger_mt("basic_logger", "logs/basic-log.txt"); spdlog::set_level(spdlog::level::debug); // Set global log level to debug logger->info("Welcome to spdlog!"); logger->error("Some error message with arg: {}", 1); return 0; } 

编译时需要链接 spdlog 库:

g++ -std=c++11 -o myapp myapp.cpp -lspdlog 

使用 log4cpp

log4cpp 是另一个流行的C++日志库。

首先,安装 log4cpp

sudo apt-get install liblog4cpp5-dev 

然后,在你的C++代码中使用它:

#include <log4cpp/Category.hh> #include <log4cpp/FileAppender.hh> #include <log4cpp/OstreamAppender.hh> #include <log4cpp/BasicLayout.hh> int main() { log4cpp::Appender* appender = new log4cpp::FileAppender("default", "application.log"); appender->setLayout(new log4cpp::BasicLayout()); log4cpp::Category& root = log4cpp::Category::getRoot(); root.addAppender(appender); root.setPriority(log4cpp::Priority::DEBUG); root.debug("Debugging info"); root.info("Information"); root.warn("Warning"); root.error("Error"); root.fatal("Fatal"); return 0; } 

编译时需要链接 log4cpp 库:

g++ -std=c++11 -o myapp myapp.cpp -llog4cpp 

3. 使用系统调用

你也可以使用系统调用来写入日志文件,但这通常不如使用文件流或第三方库方便和高效。

#include <iostream> #include <fstream> #include <string> #include <ctime> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> void logMessage(const std::string& message) { int logFd = open("app.log", O_APPEND | O_CREATE | O_WRONLY, S_IRUSR | S_IWUSR); if (logFd != -1) { time_t now = time(0); char* dt = ctime(&now); std::string logEntry = "[" + std::string(dt) + "] " + message + " "; write(logFd, logEntry.c_str(), logEntry.size()); close(logFd); } else { std::cerr << "Unable to open log file" << std::endl; } } int main() { logMessage("This is a log message."); return 0; } 

选择哪种方法取决于你的具体需求和项目的复杂性。对于大多数项目,使用第三方日志库如 spdloglog4cpp 是一个不错的选择,因为它们提供了丰富的功能和良好的性能。

0