]> git.ozlabs.org Git - petitboot/blob - lib/log/log.c
lib/log: Include timestamp prefix
[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(const char *fmt, va_list ap)
13 {
14         char hms[20] = {'\0'};
15         time_t t;
16
17         if (!logf)
18                 return;
19
20         /* Add timestamp */
21         t = time(NULL);
22         strftime(hms, sizeof(hms), "%T", localtime(&t));
23         fprintf(logf, "[%s] ", hms);
24
25         vfprintf(logf, fmt, ap);
26         fflush(logf);
27 }
28
29 void pb_log(const char *fmt, ...)
30 {
31         va_list ap;
32         va_start(ap, fmt);
33         __log(fmt, ap);
34         va_end(ap);
35 }
36
37 void pb_debug(const char *fmt, ...)
38 {
39         va_list ap;
40         if (!debug)
41                 return;
42         va_start(ap, fmt);
43         __log(fmt, ap);
44         va_end(ap);
45 }
46
47 void __pb_log_init(FILE *fp, bool _debug)
48 {
49         if (logf)
50                 fflush(logf);
51         logf = fp;
52         debug = _debug;
53 }
54
55 void pb_log_set_debug(bool _debug)
56 {
57         debug = _debug;
58 }
59
60 FILE *pb_log_get_stream(void)
61 {
62         static FILE *null_stream;
63         if (!logf) {
64                 if (!null_stream)
65                         null_stream = fopen("/dev/null", "a");
66                 return null_stream;
67         }
68         return logf;
69 }