Set loglevel og callbacks in runtime. Non static loglevel strings

This commit is contained in:
Hans Petter Dalsklev 2023-03-22 14:33:07 +01:00
parent f9ea34994b
commit 423737a870
3 changed files with 66 additions and 1 deletions

53
src/example/example.c Normal file
View File

@ -0,0 +1,53 @@
#include <stdio.h>
#include "../log.h"
extern const char *level_strings[];
void callback1(log_Event *ev)
{
char logline[128];
snprintf(logline, 128, "%-5s %s:%d: ",
level_strings[ev->level], ev->file, ev->line);
vsnprintf(logline, 128, ev->fmt, ev->ap);
printf("%s: %s\n", __func__, logline);
}
void callback2(log_Event *ev)
{
char logline[128];
snprintf(logline, 128, "%-5s %s:%d: ",
level_strings[ev->level], ev->file, ev->line);
vsnprintf(logline, 128, ev->fmt, ev->ap);
printf("%s: %s\n", __func__, logline);
}
int main()
{
log_trace("hello");
log_debug("hello");
log_info("hello");
log_warn("hello");
log_error("hello");
log_fatal("hello");
log_debug("============== update loglevel to FATAL =============");
log_set_level(LOG_FATAL);
log_trace("hello");
log_debug("hello");
log_info("hello");
log_warn("hello");
log_error("hello");
log_fatal("hello");
log_debug("===================== init log =====================");
log_add_callback(callback1, "progname", LOG_TRACE);
log_add_callback(callback2, "progname", LOG_TRACE);
log_trace("hello");
log_debug("hello");
log_info("hello");
log_warn("hello");
log_error("hello");
log_fatal("hello");
log_debug("============ update loglevels of callbacks ========");
log_set_level_callback(callback1, LOG_FATAL);
log_set_level_callback(callback2, LOG_WARN);
return 0;
}

View File

@ -39,7 +39,7 @@ static struct {
} L;
static const char *level_strings[] = {
const char *level_strings[] = {
"TRACE", "DEBUG", "INFO", "WARN", "ERROR", "FATAL"
};
@ -122,6 +122,17 @@ int log_add_callback(log_LogFn fn, void *udata, int level) {
return -1;
}
int log_set_level_callback(log_LogFn fn, int level) {
for (int i = 0; i < MAX_CALLBACKS; i++) {
if (L.callbacks[i].fn == fn) {
L.callbacks[i].level = level;
return 0;
}
}
return -1;
}
int log_add_fp(FILE *fp, int level) {
return log_add_callback(file_callback, fp, level);

View File

@ -42,6 +42,7 @@ void log_set_lock(log_LockFn fn, void *udata);
void log_set_level(int level);
void log_set_quiet(bool enable);
int log_add_callback(log_LogFn fn, void *udata, int level);
int log_set_level_callback(log_LogFn fn, int level);
int log_add_fp(FILE *fp, int level);
void log_log(int level, const char *file, int line, const char *fmt, ...);