// ============================================================================ // logger.c - 日志系统实现 // ============================================================================ #include "logger.h" #include #include #include #include static FILE* g_log_file = NULL; static LogLevel g_log_level = LOG_TRACE; static const char* level_strings[] = { "TRACE", "DEBUG", "INFO ", "WARN ", "ERROR", "FATAL" }; void logger_init(const char* log_file) { if (log_file) { g_log_file = fopen(log_file, "w"); if (g_log_file) { fprintf(g_log_file, "=== Lity3D Engine Log ===\n"); fflush(g_log_file); } } printf("=== Lity3D Engine Log ===\n"); } void logger_shutdown(void) { if (g_log_file) { fclose(g_log_file); g_log_file = NULL; } } void logger_set_level(LogLevel level) { g_log_level = level; } void logger_log(LogLevel level, const char* file, int line, const char* fmt, ...) { if (level < g_log_level) return; // 时间戳 time_t now = time(NULL); struct tm* tm_info = localtime(&now); char time_str[20]; strftime(time_str, sizeof(time_str), "%H:%M:%S", tm_info); // 文件名 (去掉路径) const char* filename = strrchr(file, '\\'); if (!filename) filename = strrchr(file, '/'); if (filename) filename++; else filename = file; // 格式化消息 char msg[2048]; va_list args; va_start(args, fmt); vsnprintf(msg, sizeof(msg), fmt, args); va_end(args); // 输出到控制台 if (level >= LOG_WARN) { fprintf(stderr, "[%s] [%s] %s:%d - %s\n", time_str, level_strings[level], filename, line, msg); } else { printf("[%s] [%s] %s:%d - %s\n", time_str, level_strings[level], filename, line, msg); } // 输出到文件 if (g_log_file) { fprintf(g_log_file, "[%s] [%s] %s:%d - %s\n", time_str, level_strings[level], filename, line, msg); fflush(g_log_file); } }