]> git.ozlabs.org Git - petitboot/blob - lib/log/log.c
discover/grub2: Allow to separate the --id argument using a space char
[petitboot] / lib / log / log.c
1
2 #include <assert.h>
3 #include <stdarg.h>
4 #include <stdlib.h>
5 #include <time.h>
6
7 #include "log.h"
8
9 static FILE *logf;
10 static bool debug;
11
12 static void __log_timestamp(void)
13 {
14         char hms[20] = {'\0'};
15         time_t t;
16
17         if (!logf)
18                 return;
19
20         t = time(NULL);
21         strftime(hms, sizeof(hms), "%T", localtime(&t));
22         fprintf(logf, "[%s] ", hms);
23 }
24
25 static void __log(const char *fmt, va_list ap)
26 {
27         if (!logf)
28                 return;
29
30         vfprintf(logf, fmt, ap);
31         fflush(logf);
32 }
33
34 void pb_log(const char *fmt, ...)
35 {
36         va_list ap;
37         va_start(ap, fmt);
38         __log_timestamp();
39         __log(fmt, ap);
40         va_end(ap);
41 }
42
43 void _pb_log_fn(const char *func, const char *fmt, ...)
44 {
45         va_list ap;
46         pb_log("%s: ", func);
47         va_start(ap, fmt);
48         __log(fmt, ap);
49         va_end(ap);
50 }
51
52 void pb_debug(const char *fmt, ...)
53 {
54         va_list ap;
55         if (!debug)
56                 return;
57         va_start(ap, fmt);
58         __log_timestamp();
59         __log(fmt, ap);
60         va_end(ap);
61 }
62
63 void _pb_debug_fn(const char *func, const char *fmt, ...)
64 {
65         va_list ap;
66         if (!debug)
67                 return;
68         pb_log("%s: ", func);
69         va_start(ap, fmt);
70         __log(fmt, ap);
71         va_end(ap);
72 }
73
74 void _pb_debug_fl(const char *func, int line, const char *fmt, ...)
75 {
76         va_list ap;
77         if (!debug)
78                 return;
79         pb_log("%s:%d: ", func, line);
80         va_start(ap, fmt);
81         __log(fmt, ap);
82         va_end(ap);
83 }
84
85 void __pb_log_init(FILE *fp, bool _debug)
86 {
87         if (logf)
88                 fflush(logf);
89         logf = fp;
90         debug = _debug;
91 }
92
93 void pb_log_set_debug(bool _debug)
94 {
95         debug = _debug;
96 }
97
98 bool pb_log_get_debug(void)
99 {
100         return debug;
101 }
102
103 FILE *pb_log_get_stream(void)
104 {
105         static FILE *null_stream;
106         if (!logf) {
107                 if (!null_stream)
108                         null_stream = fopen("/dev/null", "a");
109                 return null_stream;
110         }
111         return logf;
112 }