FILE* g_logFile = NULL; // 日志文件指针
// 初始化日志文件
void InitializeLog() {
char path[MAX_PATH];
GetModuleFileNameA(NULL, path, MAX_PATH);
// 从完整路径中提取文件名
char *filename = strrchr(path, '\\');
if (filename == NULL) {
filename = strrchr(path, '/');// 如果没有找到反斜杠,则尝试正斜杠(虽然Windows一般用反斜杠)
}
if (filename != NULL) {
filename++; // 跳过分隔符
} else {
filename = path;// 没有找到路径分隔符,则使用整个路径
}
char logFileName[256];
sprintf(logFileName, "%s_Debug.log", filename);
// 打开日志文件
g_logFile = fopen(logFileName, "a");
if (!g_logFile) {
g_logFile = fopen("LogMessage_Dubug.log", "a");// 如果无法创建日志文件,尝试使用固定名称
}
if (g_logFile) {
setvbuf(g_logFile, NULL, _IONBF, 0);// 设置缓冲区为无缓冲,确保日志即时写入
// 获取当前时间
time_t now;
time(&now);
struct tm* tm_info = localtime(&now);
char tm_buffer[80];
strftime(tm_buffer, 80, "%Y%m%d_%H%M%S", tm_info);
// 写入日志头
fprintf(g_logFile, "=== Dubug LogMessage ===\n开始时间: %s\n", tm_buffer);
}
}
// 关闭日志文件
void CloseLog() {
if (g_logFile) {
time_t now;
time(&now);
struct tm* tm_info = localtime(&now);
char tm_buffer[80];
strftime(tm_buffer, 80, "%Y%m%d_%H%M%S", tm_info);
fprintf(g_logFile, "结束时间: %s\n", tm_buffer);
fclose(g_logFile);
g_logFile = NULL;
}
}
// 记录日志消息
void LogMessage(const char* format, ...) {
if (!g_logFile) return;
// 获取当前时间
time_t now;
time(&now);
struct tm* tm_info = localtime(&now);
char timeBuf[20];
strftime(timeBuf, sizeof(timeBuf), "%H:%M:%S", tm_info);
// 写入时间戳
fprintf(g_logFile, "[%s] ", timeBuf);
// 写入日志消息
va_list args;
va_start(args, format);
vfprintf(g_logFile, format, args);
va_end(args);
fprintf(g_logFile, "\n");// 换行
// 为了调试方便,也在调试输出中显示
char msgBuf[512];
va_start(args, format);
vsprintf(msgBuf, format, args);
va_end(args);
printf("[%s] %s\n", timeBuf, msgBuf);
//#ifdef _DEBUG
// OutputDebugStringA(msgBuf);
// OutputDebugStringA("\n");
//#endif
}
#define DEBUG_INFO(format, ...) printf("[%s %s] %s: %s: %d: " format "\n", __DATE__, __TIME__, __FILE__, __func__, __LINE__, ##__VA_ARGS__);
// 记录日志消息
void LogMessageW(const wchar_t* format, ...) {
if (!g_logFile) return;
// 获取当前时间
time_t now;
time(&now);
struct tm* tm_info = localtime(&now);
char timeBuf[20];
strftime(timeBuf, sizeof(timeBuf), "%H:%M:%S", tm_info);
// 写入时间戳
fprintf(g_logFile, "[%s] ", timeBuf);
// 写入日志消息
va_list args;
va_start(args, format);
vfwprintf(g_logFile, format, args);
va_end(args);
fprintf(g_logFile, "\n");// 换行
// 为了调试方便,也在调试输出中显示
wchar_t msgBuf[512];
va_start(args, format);
vswprintf(msgBuf, format, args);
va_end(args);
wprintf(L"[%s] %s\n", timeBuf, msgBuf);
//#ifdef _DEBUG
// OutputDebugStringA(msgBuf);
// OutputDebugStringA("\n");
//#endif
}
#define DEBUG_INFOW(format, ...) printf("[%s %s] %s: %s: %d: " format "\n", __DATE__, __TIME__, __FILE__, __func__, __LINE__, ##__VA_ARGS__);
帮我整理优化代码,做成统一通用函数为.hpp文件
最新发布