在Linux環境下,使用C++進行日志記錄有多種方法。以下是一些常用的方法和庫:
iostream 和文件流最簡單的方法是使用C++標準庫中的 iostream 和文件流來記錄日志。
#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;
}
有許多成熟的第三方日志庫可以提供更豐富的功能和更好的性能。以下是一些流行的庫:
Boost.Log 是一個功能強大的日志庫,提供了靈活的配置和高效的日志記錄。
#include <boost/log/core.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/sinks/text_file_backend.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/utility/setup/console.hpp>
namespace logging = boost::log;
namespace src = boost::log::sources;
namespace sinks = boost::log::sinks;
namespace expr = boost::log::expressions;
void initLogging() {
logging::add_console_log(
std::cout,
expr::stream
<< expr::format_date_time<boost::posix_time::ptime>("TimeStamp", "%Y-%m-%d %H:%M:%S")
<< " [" << logging::trivial::severity << "] " << expr::smessage
);
logging::add_file_log(
keywords::file_name = "app.log",
keywords::rotation_size = 10 * 1024 * 1024,
keywords::time_based_rotation = sinks::file::rotation_at_time_point(0, 0, 0),
keywords::format = "[%TimeStamp%] [%Severity%] %Message%"
);
}
int main() {
initLogging();
BOOST_LOG_TRIVIAL(info) << "This is an info message.";
BOOST_LOG_TRIVIAL(warning) << "This is a warning message.";
BOOST_LOG_TRIVIAL(error) << "This is an error message.";
return 0;
}
spdlog 是一個非??焖偾乙子谑褂玫娜罩編?,支持多種輸出格式和異步日志記錄。
#include "spdlog/spdlog.h"
#include "spdlog/sinks/stdout_color_sinks.h"
#include "spdlog/sinks/basic_file_sink.h"
int main() {
auto consoleSink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
consoleSink->set_pattern("[%Y-%m-%d %H:%M:%S] [%l] %v");
spdlog::register_logger(consoleSink);
auto fileSink = std::make_shared<spdlog::sinks::basic_file_sink_mt>("app.log", true);
fileSink->set_pattern("[%Y-%m-%d %H:%M:%S] [%l] %v");
spdlog::register_logger(fileSink);
spdlog::info("This is an info message.");
spdlog::warn("This is a warning message.");
spdlog::error("This is an error message.");
return 0;
}
Linux系統提供了 syslog 接口,可以用于記錄系統級日志。
#include <syslog.h>
#include <string>
void logMessage(const std::string& message) {
openlog("myApp", LOG_PID | LOG_CONS, LOG_USER);
syslog(LOG_INFO, "%s", message.c_str());
closelog();
}
int main() {
logMessage("This is a log message.");
return 0;
}
選擇哪種方法取決于你的需求。如果你需要簡單的日志記錄,使用標準庫可能就足夠了。如果你需要更高級的功能,如異步日志記錄、多種輸出格式等,可以考慮使用第三方庫如 Boost.Log 或 spdlog。對于系統級日志,可以使用 syslog 接口。