From d89159fdb42878d283da47cfb25685009cd9c5c7 Mon Sep 17 00:00:00 2001 From: jcmichelou Date: Sat, 2 Sep 2017 16:56:45 +0200 Subject: [PATCH] debug.[hc]: Add a log handler callback. --- include/coap/debug.h | 5 +++++ libcoap-1.sym | 1 + src/debug.c | 43 +++++++++++++++++++++++++++++-------------- 3 files changed, 35 insertions(+), 14 deletions(-) diff --git a/include/coap/debug.h b/include/coap/debug.h index 64e965be..f475ad72 100644 --- a/include/coap/debug.h +++ b/include/coap/debug.h @@ -41,6 +41,11 @@ coap_log_t coap_get_log_level(void); /** Sets the log level to the specified value. */ void coap_set_log_level(coap_log_t level); +typedef void (*coap_log_handler_t) (coap_log_t level, const char *message); + +/** Add a custom log callback, use NULL to reset default handler */ +void coap_set_log_handler(coap_log_handler_t handler); + /** Returns a zero-terminated string with the name of this library. */ const char *coap_package_name(void); diff --git a/libcoap-1.sym b/libcoap-1.sym index d893ad5c..c082d67c 100644 --- a/libcoap-1.sym +++ b/libcoap-1.sym @@ -145,6 +145,7 @@ coap_session_set_mtu coap_session_str coap_set_app_data coap_set_event_handler +coap_set_log_handler coap_set_log_level coap_show_pdu coap_socket_bind_udp diff --git a/src/debug.c b/src/debug.c index c9b26c8f..06849287 100644 --- a/src/debug.c +++ b/src/debug.c @@ -489,30 +489,45 @@ coap_show_pdu(const coap_pdu_t *pdu) { fflush(COAP_DEBUG_FD); } +static coap_log_handler_t log_handler = NULL; + +void coap_set_log_handler(coap_log_handler_t handler) { + log_handler = handler; +} void coap_log_impl(coap_log_t level, const char *format, ...) { - char timebuf[32]; - coap_tick_t now; - va_list ap; - FILE *log_fd; if (maxlog < level) return; + + if (log_handler) { + char message[128]; + va_list ap; + va_start(ap, format); + vsnprintf( message, sizeof(message), format, ap); + va_end(ap); + log_handler(level, message); + } else { + char timebuf[32]; + coap_tick_t now; + va_list ap; + FILE *log_fd; - log_fd = level <= LOG_CRIT ? COAP_ERR_FD : COAP_DEBUG_FD; + log_fd = level <= LOG_CRIT ? COAP_ERR_FD : COAP_DEBUG_FD; - coap_ticks(&now); - if (print_timestamp(timebuf,sizeof(timebuf), now)) - fprintf(log_fd, "%s ", timebuf); + coap_ticks(&now); + if (print_timestamp(timebuf,sizeof(timebuf), now)) + fprintf(log_fd, "%s ", timebuf); - if (level <= LOG_DEBUG) - fprintf(log_fd, "%s ", loglevels[level]); + if (level <= LOG_DEBUG) + fprintf(log_fd, "%s ", loglevels[level]); - va_start(ap, format); - vfprintf(log_fd, format, ap); - va_end(ap); - fflush(log_fd); + va_start(ap, format); + vfprintf(log_fd, format, ap); + va_end(ap); + fflush(log_fd); + } } static struct packet_num_interval {