1、log.h中宏定义
#include <stdio.h>
#include <iostream>
#include <chrono>
#include <ctime>
#include <mutex>#define LOG_PRINTF(format, ...) do{ \static std::mutex log_mutex;\auto now = std::chrono::system_clock::now();\std::time_t now_time_t = std::chrono::system_clock::to_time_t(now);\auto duration = now.time_since_epoch();\auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count() % 1000;\std::lock_guard<std::mutex> guard(log_mutex);\std::tm now_tm = *std::localtime(&now_time_t);\printf("[%04d-%02d-%02d %02d:%02d:%02d.%03lld]" format, \now_tm.tm_year + 1900 , now_tm.tm_mon + 1, now_tm.tm_mday, \now_tm.tm_hour, now_tm.tm_min , now_tm.tm_sec, milliseconds , ##__VA_ARGS__);\
}while(0)
2、main.cpp 使用
FILE *logFile = freopen("log.txt","a",stdout);
if(logFile == NULL) {perror("Failed to open or creat log file");
}
fclose(logFile); // 关闭文件,退出程序使用
3、Qt 中使用示例
3.1 修改前
int main(int argc, char *argv[])
{QApplication a(argc, argv);MainWindow w;w.show();return a.exec(); // 运行 Qt 事件循环
}
3.2 修改后
int main(int argc, char *argv[])
{QApplication a(argc, argv);FILE *logFile = freopen("log.txt","a",stdout);if(logFile == NULL) {perror("Failed to open or creat log file");}MainWindow w;w.show();int result = a.exec(); // 运行 Qt 事件循环fclose(logFile); // 退出 Qt 事件循环后关闭日志文件return result;
}