本文旨在分享一种自定义的LOG模板,该LOG可以打印文件中的debug相关信息,同时可以以不同的颜色显示。
LOG级别有5种类型,用户可以根据使用的具体场景进行选择和使用。
// g++ logger.cpp -o test -std=c++17 -pthread
#include <iostream>
#include <fstream>
#include <string>
#include <chrono>
#include <ctime>
#include <thread>
#include <mutex>
#include <queue>
#include <condition_variable>
#include <atomic>
#include <iomanip>
#include <sstream>
#include <cstdio>
#include <cstdlib> // for std::exit
class Logger {
public:
enum LogLevel {
DEBUG,
INFO,
WARNING,
ERROR,
FATAL
};
Logger(const std::string& filename, LogLevel level = INFO, size_t maxSize = 1048576)
: logLevel(level), maxFileSize(maxSize), stopLogging(false) {
logFile.open(filename, std::ios::app);
logThread = std::thread(&Logger::processQueue, this);
}
~Logger() {
stopLogging = true;
cv.notify_all();
if (logThread.joinable()) {
logThread.join();
}
if (logFile.is_open()) {
logFile.close();
}
}
void log(LogLevel level, const std::string& message, const char* file, const char* function, int line) {
if (level >= logLevel) {
std::lock_guard<std::mutex> lock(mtx);
std::string logMessage = formatMessage(level, message, file, function, line);
logQueue.push(logMessage);
cv.notify_one();
checkLogFileSize();
// 输出到终端,并根据级别设置颜色
std::cout << getColoredMessage(level, logMessage) << std::endl;
// 如果日志级别大于 ERROR,终止程序
// if (level >= ERROR) {
// std::cerr << "程序将终止!" << std::endl;
// std::exit(EXIT_FAILURE);
// }
}
}
private:
std::ofstream logFile;
std::thread logThread;
std::mutex mtx;
std::condition_variable cv;
std::queue<std::string> logQueue;
std::atomic<bool> stopLogging;
LogLevel logLevel;
size_t maxFileSize;
std::string getCurrentTime() {
auto now = std::chrono::system_clock::now();
auto nowTime = std::chrono::system_clock::to_time_t(now);
std::ostringstream oss;
oss << std::put_time(std::localtime(&nowTime), "%H:%M:%S");
return oss.str();
}
std::string formatMessage(LogLevel level, const std::string& message, const char* file, const char* function, int
line) {
return getCurrentTime() + " [" + logLevelToString(level) + "] " + file
+ ":L" + std::to_string(line) + " " + message;
}
std::string logLevelToString(LogLevel level) {
switch (level) {
case DEBUG : return "DLOG";
case INFO : return "ILOG";
case WARNING: return "WLOG";
case ERROR : return "ELOG";
case FATAL : return "FLOG";
default: return "UNKNOWN";
}
}
std::string getColoredMessage(LogLevel level, const std::string& message) {
switch (level) {
case DEBUG:
case INFO:
return "\033[32m" + message + "\033[0m"; // Green
case WARNING:
return "\033[33m" + message + "\033[0m"; // Yellow
case ERROR:
return "\033[31m" + message + "\033[0m"; // Red
case FATAL:
return "\033[41;37m" + message + "\033[0m"; // Red background with white text
default:
return message; // No color
}
}
void processQueue() {
while (!stopLogging || !logQueue.empty()) {
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, [this]{ return stopLogging || !logQueue.empty(); });
while (!logQueue.empty()) {
logFile << logQueue.front() << std::endl;
logQueue.pop();
}
}
}
void checkLogFileSize() {
logFile.flush();
if (logFile.tellp() >= static_cast<std::streampos>(maxFileSize)) {
logFile.close();
rotateLogFile();
logFile.open("logfile.txt", std::ios::app);
}
}
void rotateLogFile() {
std::string oldFileName = "logfile.txt";
std::string newFileName = "logfile_old.txt";
std::remove(newFileName.c_str()); // Remove the old rotated file if it exists
std::rename(oldFileName.c_str(), newFileName.c_str()); // Rename the current log file
}
};
#define LOG(level, message) logger.log(level, message, __FILE__, __FUNCTION__, __LINE__)
int main() {
Logger logger("logfile.txt", Logger::DEBUG, 1048576); // 1MB
LOG(Logger::INFO, "Test program is called.");
LOG(Logger::WARNING, "Warning! This is a message!");
LOG(Logger::ERROR, "This is a error message, please attention!");
LOG(Logger::FATAL, "Fatal error!");
std::this_thread::sleep_for(std::chrono::seconds(2)); // 确保日志写入
return 0;
}
执行结果如下图所示: