2024-10-10 20:11:57 +08:00
|
|
|
#include "log.h"
|
2024-10-15 01:36:02 +08:00
|
|
|
#include <stdio.h>
|
|
|
|
#include <stdlib.h>
|
|
|
|
#include <stdarg.h>
|
|
|
|
#include <time.h>
|
2024-10-10 20:11:57 +08:00
|
|
|
|
|
|
|
const char* get_current_time()
|
|
|
|
{
|
|
|
|
static char buffer[20];
|
|
|
|
time_t now = time(NULL);
|
|
|
|
struct tm* tm_info = localtime(&now);
|
|
|
|
strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", tm_info);
|
|
|
|
return buffer;
|
|
|
|
}
|
|
|
|
|
2024-10-15 01:36:02 +08:00
|
|
|
void log_message(LogLevel level, const char* format, ...)
|
2024-10-10 20:11:57 +08:00
|
|
|
{
|
|
|
|
const char* level_strings[] = { "INFO", "WARNING", "ERROR" };
|
|
|
|
|
|
|
|
// Open the log file in append mode
|
|
|
|
FILE* log_file = fopen("logfile.txt", "a");
|
|
|
|
if (log_file == NULL) {
|
|
|
|
fprintf(stderr, "Could not open log file for writing.\n");
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2024-10-15 01:36:02 +08:00
|
|
|
va_list args;
|
|
|
|
|
2024-10-10 20:11:57 +08:00
|
|
|
// Write the log message to the file
|
2024-10-15 01:36:02 +08:00
|
|
|
va_start(args, format);
|
|
|
|
fprintf(log_file, "[%s] [%s] ", get_current_time(), level_strings[level]);
|
|
|
|
vfprintf(log_file, format, args);
|
|
|
|
fprintf(log_file, "\n");
|
|
|
|
va_end(args);
|
|
|
|
// Write to stdout
|
|
|
|
va_start(args, format);
|
|
|
|
printf("[%s] ", level_strings[level]);
|
|
|
|
vprintf(format, args);
|
|
|
|
printf("\n");
|
|
|
|
va_end(args);
|
2024-10-10 20:11:57 +08:00
|
|
|
|
|
|
|
// Close the log file
|
|
|
|
fclose(log_file);
|
|
|
|
}
|