From 288f12d36843b6e404adb35857fcd87943e63944 Mon Sep 17 00:00:00 2001 From: Mitja Felicijan Date: Sat, 24 Jan 2026 17:17:21 +0100 Subject: Engage! --- logging.c | 71 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 logging.c (limited to 'logging.c') diff --git a/logging.c b/logging.c new file mode 100644 index 0000000..4f383c1 --- /dev/null +++ b/logging.c @@ -0,0 +1,71 @@ +#define _POSIX_C_SOURCE 200809L + +#include +#include +#include +#include +#include +#include + +#include "glitch.h" + +static LogLevel max_level = LOG_INFO; + +static const char* level_strings[] = { + "INFO", + "DEBUG", + "WARN", + "ERROR", +}; + +static const char* level_colors[] = { + COLOR_INFO, + COLOR_DEBUG, + COLOR_WARNING, + COLOR_ERROR, +}; + +void set_log_level(LogLevel level) { + max_level = level; +} + +LogLevel get_log_level_from_env(void) { + const char *env = getenv("LOG_LEVEL"); + if (env) { + int level = atoi(env); + if (level >= 0 && level <= 3) { + return (LogLevel)level; + } + } + + return max_level; +} + +void log_message(FILE *stream, LogLevel level, const char* format, ...) { + if (max_level < level) return; + + struct timeval tv; + gettimeofday(&tv, NULL); + struct tm* tm_info = localtime(&tv.tv_sec); + + char time_str[24]; + strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", tm_info); + + const char *color = isatty(fileno(stream)) ? level_colors[level] : ""; + const char *reset = isatty(fileno(stream)) ? COLOR_RESET : ""; + + const char* log_format = "%s[%s.%03d] [%-5s] "; + fprintf(stream, log_format, + color, + time_str, + (int)(tv.tv_usec / 1000), + level_strings[level]); + + va_list args; + va_start(args, format); + vfprintf(stream, format, args); + va_end(args); + + fprintf(stream, "%s\n", reset); + fflush(stream); +} -- cgit v1.2.3