8662f05f351bdb8870b02c73d05738f4c00a4881
[lemu] / notify.c
1 #define _GNU_SOURCE 1
2
3 #include <stdlib.h>
4 #include <stdio.h>
5 #include <stdarg.h>
6 #include <string.h>
7 #include <errno.h>
8
9 #include "notify.h"
10
11 /*
12 * Generic console notifier.
13 */
14
15 static void
16 notify_fn_default_(int level, const char * func_name, const char * fmt, ...)
17 {
18 FILE *f = (level <= 1) ? stderr : stdout;
19 static const char * const levels[] = { "FATAL", "ERROR", "INFO", "DEBUG" };
20 const int levels_num = sizeof levels / sizeof *levels;
21 va_list ap;
22
23 flockfile(f);
24
25 fputs_unlocked((func_name && *func_name) ? func_name : "[null]", f);
26 fputs_unlocked(": --", f);
27 if (level >= 0
28 && level <= levels_num) {
29 fputs_unlocked(levels[level], f);
30 } else {
31 fprintf(f, "%d", level);
32 }
33 fputs_unlocked("-- ", f);
34
35 va_start(ap, fmt);
36 vfprintf(f, fmt, ap);
37 va_end(ap);
38
39 fputc_unlocked('\n', f);
40 fflush_unlocked(f);
41
42 funlockfile(f);
43
44 }
45
46 void (* notify_fn)(int level, const char *func_name, const char *msg, ...) __attribute__((format(printf, 3, 4))) = notify_fn_default_;
47
48 void
49 notify_fn_set(void (* fn)(int level, const char *func_name, const char *fmt, ...))
50 {
51 notify_fn = fn;
52 }