From 3e4e10c1c1203d605aeceafa8f15e6a3a4aa8033 Mon Sep 17 00:00:00 2001 From: verdant Date: Tue, 21 Jul 2026 18:53:18 +0800 Subject: Add logging system --- log.c | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ log.h | 16 ++++++++++++++++ 2 files changed, 73 insertions(+) create mode 100644 log.c create mode 100644 log.h diff --git a/log.c b/log.c new file mode 100644 index 0000000..305a666 --- /dev/null +++ b/log.c @@ -0,0 +1,57 @@ +#include "log.h" + +#include +#include +#include +#include +#include + +#include "err.h" +#include "utils.h" + +FILE* log_file = NULL; + +void log_init(void) { + if (is_debug()) { + log_file = fopen("./log", "a"); + } else { + log_file = fopen(LOG_FILEPATH, "a"); + } + + if (!log_file) { + die("Faild to open log file"); + } +} + +void log_write(log_level level, const char* fmt, ...) { + char* level_str; + + if (level == LOG_INFO) level_str = "INFO"; + if (level == LOG_WARN) level_str = "WARN"; + if (level == LOG_ERR) level_str = "ERR"; + + time_t rawtime; + struct tm* timeinfo; + char time_str[32]; + + time(&rawtime); + timeinfo = localtime(&rawtime); + strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", timeinfo); + + fprintf(log_file, "[%s] [%s] ", time_str, level_str); + + va_list ap; + va_start(ap, fmt); + vfprintf(log_file, fmt, ap); + va_end(ap); + + fprintf(log_file, "\n"); + fflush(log_file); +} + +void log_end(FILE* log_file) { + if (log_file) { + fclose(log_file); + log_file = NULL; + } +} diff --git a/log.h b/log.h new file mode 100644 index 0000000..e95039f --- /dev/null +++ b/log.h @@ -0,0 +1,16 @@ +#ifndef SS_LOG_H +#define SS_LOG_H + +#define LOG_FILEPATH "./log" + +typedef enum { + LOG_INFO, + LOG_WARN, + LOG_ERR, +} log_level; + +void log_init(void); + +void log_write(log_level level, const char* fmt, ...); + +#endif /* SS_LOG_H */ -- cgit v1.2.3