sdl-audio/log.c

45 lines
1023 B
C
Raw Normal View History

2024-10-10 20:11:57 +08:00
#include "log.h"
#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;
}
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;
}
va_list args;
2024-10-10 20:11:57 +08:00
// Write the log message to the file
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);
}