From a97300a77b2c10fbd8eedc07e658f67f7a3ec7a5 Mon Sep 17 00:00:00 2001 From: Sandy Carter Date: Wed, 3 Jan 2024 00:13:15 -0500 Subject: [PATCH] logging: Add handler pointer for logging Default to old stderr logging method. Add function pointer and userdata pointer as static globals. --- lib/libunshield.h | 2 ++ lib/log.c | 25 +++++++++++++++++++++---- 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/lib/libunshield.h b/lib/libunshield.h index d7e2dda..18eb2bb 100644 --- a/lib/libunshield.h +++ b/lib/libunshield.h @@ -32,7 +32,9 @@ typedef struct _Unshield Unshield; #define UNSHIELD_LOG_LEVEL_HIGHEST 4 +typedef void (UnshieldLogCallback)(void* userdata, int level, const char* file, int line, const char* format, va_list ap); void unshield_set_log_level(int level); +void unshield_set_log_handler(UnshieldLogCallback* handler, void* userdata); /* Open/close functions diff --git a/lib/log.c b/lib/log.c index 42673b8..f573641 100644 --- a/lib/log.c +++ b/lib/log.c @@ -4,25 +4,42 @@ /* evil static data */ static int current_log_level = UNSHIELD_LOG_LEVEL_HIGHEST; +static UnshieldLogCallback* current_log_handler = NULL; +static void* current_log_handler_userdata = NULL; void unshield_set_log_level(int level) { current_log_level = level; } -void _unshield_log(int level, const char* file, int line, const char* format, ...) +void unshield_set_log_handler(UnshieldLogCallback* handler, void* userdata) { - va_list ap; + current_log_handler = handler; + current_log_handler_userdata = userdata; +} + +void unshield_default_log_handler(void* userdata, int level, const char* file, int line, const char* format, va_list ap) +{ + (void)userdata; if (level > current_log_level) return; fprintf(stderr, "[%s:%i] ", file, line); - va_start(ap, format); vfprintf(stderr, format, ap); - va_end(ap); fprintf(stderr, "\n"); } +void _unshield_log(int level, const char* file, int line, const char* format, ...) +{ + va_list ap; + + if (current_log_handler == NULL) + unshield_set_log_handler(unshield_default_log_handler, NULL); + + va_start(ap, format); + current_log_handler(current_log_handler_userdata, level, file, line, format, ap); + va_end(ap); +}