#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
class Logger {
public:
Logger(const std::string& filename) : logFile(filename, std::ios::out) {
if (!logFile.is_open()) {
std::cerr << "Unable to open log file: " << filename << std::endl;
}
}
~Logger() {
if (logFile.is_open()) {
logFile.close();
}
}
void log(const std::string& message) {
if (logFile.is_open()) {
logFile << getCurrentTime() << " - " << message << std::endl;
} else {
std::cerr << "Log file is not open." << std::endl;
}
}
private:
std::ofstream logFile;
std::string getCurrentTime() {
std::time_t now = std::time(nullptr);
char buf[20];
std::strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", std::localtime(&now));
return std::string(buf);
}
};
int main() {
Logger logger("app.log");
logger.log("Application started.");
logger.log("This is a test log message.");
return 0;
}
类定义:
Logger 类用于管理日志文件的打开、关闭和写入操作。构造函数:
析构函数:
log 方法:
getCurrentTime 方法:
YYYY-MM-DD HH:MM:SS。main 函数:
Logger 对象,指定日志文件名为 app.log。log 方法记录两条日志消息。这个示例展示了如何使用 C++ 实现一个简单的日志记录功能。
上一篇:c++ string转char
下一篇:c++ map添加元素的方法
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站