From 59062e77589a935f42249ba52d773c963e8f220b Mon Sep 17 00:00:00 2001 From: Stefano Babic Date: Thu, 16 Sep 2021 12:24:45 +0200 Subject: [PATCH] zck_log: allow a callback for logging When zck is used as library, the caller has already its own LOG system. It is nice to redirect zck's log into the main logger. ZCK can already write into a fd specified by the user, but this add complexity in case it cannot be mapped, for example if LOG should be sent to network or is managed in a different way. iNot only, information like loglevel are lost. Signed-off-by: Stefano Babic --- include/zck.h.in | 4 ++++ src/lib/log.c | 18 +++++++++++++++--- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/include/zck.h.in b/include/zck.h.in index a053b30..ed646b7 100644 --- a/include/zck.h.in +++ b/include/zck.h.in @@ -5,6 +5,7 @@ #include #include +#include #include typedef enum zck_hash { @@ -129,6 +130,9 @@ const char *zck_get_error(zckCtx *zck); /* Clear error message * Returns 1 if message was cleared, 0 if error is fatal and can't be cleared */ bool zck_clear_error(zckCtx *zck); +/* Set a callback for logs instead to write into a fd */ +typedef void (*logcallback)(const char *function, zck_log_type lt, const char *format, va_list args); +void zck_set_log_callback(logcallback function); /******************************************************************* * Miscellaneous utilities diff --git a/src/lib/log.c b/src/lib/log.c index b6598d8..a238b87 100644 --- a/src/lib/log.c +++ b/src/lib/log.c @@ -36,6 +36,8 @@ static zck_log_type log_level = ZCK_LOG_ERROR; static int log_fd = STDERR_FILENO; +static logcallback callback = NULL; + void PUBLIC zck_set_log_level(zck_log_type ll) { log_level = ll; } @@ -44,14 +46,24 @@ void PUBLIC zck_set_log_fd(int fd) { log_fd = fd; } +void PUBLIC zck_set_log_callback(logcallback function) { + if (!function) + return; + callback = function; +} + void zck_log_v(const char *function, zck_log_type lt, const char *format, va_list args) { if(lt < log_level || log_level == ZCK_LOG_ERROR) return; - dprintf(log_fd, "%s: ", function); - vdprintf(log_fd, format, args); - dprintf(log_fd, "\n"); + if (callback) { + callback(function, lt, format, args); + } else { + dprintf(log_fd, "%s: ", function); + vdprintf(log_fd, format, args); + dprintf(log_fd, "\n"); + } } void zck_log_wf(const char *function, zck_log_type lt, const char *format, ...) { -- 2.30.2