69 lines
1.6 KiB
C
69 lines
1.6 KiB
C
#include "Log.h"
|
|
#include <stdarg.h>
|
|
#include <time.h>
|
|
#include <string.h>
|
|
|
|
static FILE* LogFile = NULL; // 日志文件指针
|
|
static char DefaultLogFile[] = "libdm_log.txt"; // 默认日志文件
|
|
|
|
// 获取当前时间字符串
|
|
static void GetTimeStr(char* buffer, size_t size) {
|
|
time_t now = time(NULL);
|
|
struct tm* t = localtime(&now);
|
|
strftime(buffer, size, "%Y-%m-%d %H:%M:%S", t);
|
|
}
|
|
|
|
// 日志级别对应的字符串
|
|
static const char* GetLogLevelStr(LogLevel level) {
|
|
switch (level) {
|
|
case Info: return "INFO";
|
|
case Warn: return "WARNING";
|
|
case Error: return "ERROR";
|
|
case Debug: return "DEBUG";
|
|
default: return "UNKNOWN";
|
|
}
|
|
}
|
|
|
|
// 初始化日志文件
|
|
void InitLog(const char* logFilePath) {
|
|
if (LogFile) {
|
|
CloseLog(); // 关闭已有文件
|
|
}
|
|
|
|
const char* filePath = logFilePath ? logFilePath : DefaultLogFile;
|
|
LogFile = fopen(filePath, "a"); // 以追加模式打开日志文件
|
|
if (!LogFile) {
|
|
fprintf(stderr, "Failed to open log file: %s\n", filePath);
|
|
}
|
|
}
|
|
|
|
// 写日志的核心函数
|
|
void WriteLog(LogLevel level, const char* format, ...) {
|
|
if (!LogFile) {
|
|
InitLog(NULL); // 如果未初始化日志文件,则使用默认文件
|
|
}
|
|
|
|
if (LogFile) {
|
|
char timeStr[20];
|
|
GetTimeStr(timeStr, sizeof(timeStr));
|
|
|
|
fprintf(LogFile, "[%s] [%s] ", timeStr, GetLogLevelStr(level));
|
|
|
|
va_list args;
|
|
va_start(args, format);
|
|
vfprintf(LogFile, format, args); // 格式化写入日志信息
|
|
va_end(args);
|
|
|
|
fprintf(LogFile, "\n");
|
|
fflush(LogFile); // 确保日志实时写入
|
|
}
|
|
}
|
|
|
|
// 关闭日志文件
|
|
void CloseLog() {
|
|
if (LogFile) {
|
|
fclose(LogFile);
|
|
LogFile = NULL;
|
|
}
|
|
}
|