]> git.ozlabs.org Git - petitboot/blob - lib/log/log.c
lib/process: Add process_get_stdout
[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_log_fn(const char *func, const char *fmt, ...)
38 {
39         va_list ap;
40         pb_log("%s: ", func);
41         va_start(ap, fmt);
42         __log(fmt, ap);
43         va_end(ap);
44 }
45
46 void pb_debug(const char *fmt, ...)
47 {
48         va_list ap;
49         if (!debug)
50                 return;
51         va_start(ap, fmt);
52         __log(fmt, ap);
53         va_end(ap);
54 }
55
56 void _pb_debug_fn(const char *func, const char *fmt, ...)
57 {
58         va_list ap;
59         if (!debug)
60                 return;
61         pb_log("%s: ", func);
62         va_start(ap, fmt);
63         __log(fmt, ap);
64         va_end(ap);
65 }
66
67 void _pb_debug_fl(const char *func, int line, const char *fmt, ...)
68 {
69         va_list ap;
70         if (!debug)
71                 return;
72         pb_log("%s:%d: ", func, line);
73         va_start(ap, fmt);
74         __log(fmt, ap);
75         va_end(ap);
76 }
77
78 void __pb_log_init(FILE *fp, bool _debug)
79 {
80         if (logf)
81                 fflush(logf);
82         logf = fp;
83         debug = _debug;
84 }
85
86 void pb_log_set_debug(bool _debug)
87 {
88         debug = _debug;
89 }
90
91 bool pb_log_get_debug(void)
92 {
93         return debug;
94 }
95
96 FILE *pb_log_get_stream(void)
97 {
98         static FILE *null_stream;
99         if (!logf) {
100                 if (!null_stream)
101                         null_stream = fopen("/dev/null", "a");
102                 return null_stream;
103         }
104         return logf;
105 }