zck_log: allow a callback for logging
authorStefano Babic <sbabic@denx.de>
Thu, 16 Sep 2021 10:24:45 +0000 (12:24 +0200)
committerStefano Babic <sbabic@denx.de>
Thu, 23 Sep 2021 15:52:43 +0000 (17:52 +0200)
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 <sbabic@denx.de>
include/zck.h.in
src/lib/log.c

index a053b303c43a15d7b291362dd31bde6ee20b4db7..ed646b78271bda4d98c215762bcac653cc36ff99 100644 (file)
@@ -5,6 +5,7 @@
 
 #include <stdlib.h>
 #include <stdbool.h>
+#include <stdarg.h>
 #include <sys/types.h>
 
 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
index b6598d8d43792943ea27fe493561f67317fa72fe..a238b8709348747c8d9eb9fbdae8d0a2eb95fcfe 100644 (file)
@@ -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, ...) {