]> mj.ucw.cz Git - libucw.git/blob - ucw/log.c
hashtable: Implemented new HASH_TABLE_VARS parameter.
[libucw.git] / ucw / log.c
1 /*
2  *      UCW Library -- Logging
3  *
4  *      (c) 1997--2009 Martin Mares <mj@ucw.cz>
5  *      (c) 2008 Tomas Gavenciak <gavento@ucw.cz>
6  *
7  *      This software may be freely distributed and used according to the terms
8  *      of the GNU Lesser General Public License.
9  */
10
11 #include "ucw/lib.h"
12 #include "ucw/log.h"
13 #include "ucw/log-internal.h"
14 #include "ucw/simple-lists.h"
15
16 #include <stdio.h>
17 #include <stdlib.h>
18 #include <string.h>
19 #include <unistd.h>
20 #include <sys/time.h>
21 #include <time.h>
22 #include <alloca.h>
23 #include <errno.h>
24
25 char *log_title;
26 int log_pid;
27 void (*log_die_hook)(void);
28
29 static void NONRET do_die(void);
30
31 /*** The default log stream, which logs to stderr ***/
32
33 static int default_log_handler(struct log_stream *ls UNUSED, struct log_msg *m)
34 {
35   // This is a completely bare version of the log-file module. Errors are ignored.
36   write(2, m->m, m->m_len);
37   return 0;
38 }
39
40 struct log_stream log_stream_default = {
41   .name = "stderr",
42   .use_count = 1000000,
43   .handler = default_log_handler,
44   .levels = ~0U,
45   .types = ~0U,
46   .msgfmt = LSFMT_DEFAULT,
47   // an empty clist
48   .substreams.head = {
49     .next = (cnode *) &log_stream_default.substreams.head,
50     .prev = (cnode *) &log_stream_default.substreams.head,
51   },
52 };
53
54 /*** Registry of streams and their identifiers ***/
55
56 struct lsbuf_t log_streams;             /* A growing array of pointers to log_streams */
57 int log_streams_after = 0;              /* The first never-used index in log_streams.ptr */
58
59 /*
60  *  Find a stream by its identifier given as LS_SET_STRNUM(flags).
61  *  Returns NULL if the stream doesn't exist or it's invalid.
62  *
63  *  If the log-stream machinery has not been initialized (which is normal for programs
64  *  with no fancy logging), the log_streams gbuf is empty and this function only
65  *  translates stream #0 to the static log_stream_default.
66  */
67
68 struct log_stream *
69 log_stream_by_flags(uns flags)
70 {
71   int n = LS_GET_STRNUM(flags);
72   if (n < 0 || n >= log_streams_after || log_streams.ptr[n]->regnum == -1)
73     return (n ? NULL : &log_stream_default);
74   return log_streams.ptr[n];
75 }
76
77 /*** Known message types ***/
78
79 char **log_type_names;
80
81 char *
82 log_type_name(uns flags)
83 {
84   uns type = LS_GET_TYPE(flags);
85
86   if (!log_type_names || !log_type_names[type])
87     return "default";
88   else
89     return log_type_names[type];
90 }
91
92 /*** Logging ***/
93
94 void
95 vmsg(uns cat, const char *fmt, va_list args)
96 {
97   struct timeval tv;
98   struct tm tm;
99   va_list args2;
100   char stime[24];
101   char sutime[12];
102   char msgbuf[256];
103   char *p;
104   int len;
105   uns sighandler = cat & L_SIGHANDLER;
106   struct log_stream *ls;
107   struct log_msg m = { .flags = cat };
108
109   /* Find the destination stream */
110   if (sighandler)
111     ls = &log_stream_default;
112   else if (!(ls = log_stream_by_flags(cat)))
113     {
114       msg((LS_CTRL_MASK&cat)|L_WARN, "No log_stream with number %d! Logging to the default log.", LS_GET_STRNUM(cat));
115       ls = &log_stream_default;
116     }
117
118   /* Get the current time */
119   if (!sighandler)
120     {
121       /* CAVEAT: These calls are not safe in signal handlers. */
122       gettimeofday(&tv, NULL);
123       m.tv = &tv;
124       if (localtime_r(&tv.tv_sec, &tm))
125         m.tm = &tm;
126     }
127
128   /* Generate time strings */
129   if (m.tm)
130     {
131       strftime(stime, sizeof(stime), "%Y-%m-%d %H:%M:%S", &tm);
132       snprintf(sutime, sizeof(sutime), ".%06d", (int)tv.tv_usec);
133       m.stime = stime;
134       m.sutime = sutime;
135     }
136   else
137     {
138       m.stime = "\?\?\?\?-\?\?-\?\? \?\?:\?\?:\?\?";
139       m.sutime = ".\?\?\?\?\?\?";
140     }
141
142   /* Generate the message string */
143   va_copy(args2, args);
144   len = vsnprintf(msgbuf, sizeof(msgbuf), fmt, args2);
145   va_end(args2);
146   if (len < (int) sizeof(msgbuf) || sighandler)
147     m.raw_msg = msgbuf;
148   else
149     {
150       m.raw_msg = xmalloc(len+1);
151       vsnprintf(m.raw_msg, len+1, fmt, args);
152     }
153
154   /* Remove non-printable characters and newlines */
155   p = m.raw_msg;
156   while (*p)
157     {
158       if (*p >= 0 && *p < 0x20 && *p != '\t')
159         *p = 0x7f;
160       p++;
161     }
162
163   /* Pass the message to the log_stream */
164   if (log_pass_msg(0, ls, &m))
165     {
166       /* Error (such as infinite loop) occurred */
167       log_pass_msg(0, &log_stream_default, &m);
168     }
169
170   if (m.raw_msg != msgbuf)
171     xfree(m.raw_msg);
172 }
173
174 static void
175 log_report_err(struct log_stream *ls, struct log_msg *m, int err)
176 {
177   if (m->flags & L_LOGGER_ERR)
178     return;
179   if (ls->stream_flags & LSFLAG_ERR_REPORTED)
180     return;
181   ls->stream_flags |= LSFLAG_ERR_REPORTED;
182
183   struct log_msg errm = *m;
184   char errbuf[128];
185   char *name = (ls->name ? : "<unnamed>");
186
187   errm.flags = ((ls->stream_flags & LSFLAG_ERR_IS_FATAL) ? L_FATAL : L_ERROR);
188   errm.flags |= L_LOGGER_ERR | (m->flags & LS_CTRL_MASK);
189   errm.raw_msg = errbuf;
190   if (err == EDEADLK)
191     snprintf(errbuf, sizeof(errbuf), "Error logging to %s: Maximum nesting level of log streams exceeded", name);
192   else
193     {
194       errno = err;
195       snprintf(errbuf, sizeof(errbuf), "Error logging to %s: %m", name);
196     }
197   log_pass_msg(0, &log_stream_default, &errm);
198
199   if (ls->stream_flags & LSFLAG_ERR_IS_FATAL)
200     do_die();
201 }
202
203 /* Maximal depth of log_pass_msg recursion */
204 #define LS_MAX_DEPTH 64
205
206 int
207 log_pass_msg(int depth, struct log_stream *ls, struct log_msg *m)
208 {
209   ASSERT(ls);
210
211   /* Check recursion depth */
212   if (depth > LS_MAX_DEPTH)
213     {
214       log_report_err(ls, m, EDEADLK);
215       return 1;
216     }
217
218   /* Filter by level, type and hook function */
219   if (!((1 << LS_GET_LEVEL(m->flags)) & ls->levels) ||
220       !((1 << LS_GET_TYPE(m->flags)) & ls->types) ||
221       ls->filter && ls->filter(ls, m))
222     return 0;
223
224   /* Pass the message to substreams */
225   CLIST_FOR_EACH(simp_node *, s, ls->substreams)
226     if (log_pass_msg(depth+1, s->p, m))
227       return 1;
228
229   /* Will pass to the handler of this stream... is there any? */
230   if (!ls->handler)
231     return 0;
232
233   /* Will print a message type? */
234   char *type = NULL;
235   if ((ls->msgfmt & LSFMT_TYPE) && LS_GET_TYPE(m->flags))
236     type = log_type_name(m->flags);
237
238   /* Upper bound on message length */
239   int len = strlen(m->raw_msg) + strlen(m->stime) + strlen(m->sutime) + 32;
240   if (log_title)
241     len += strlen(log_title);
242   if (ls->name)
243     len += strlen(ls->name);
244   if (type)
245     len += strlen(type) + 3;
246
247   /* Get a buffer and format the message */
248   char *free_buf = NULL;
249   if (len <= 256 || (m->flags & L_SIGHANDLER))
250     m->m = alloca(len);
251   else
252     m->m = free_buf = xmalloc(len);
253   char *p = m->m;
254
255   /* Level (2 chars) */
256   if (ls->msgfmt & LSFMT_LEVEL)
257     {
258       *p++ = LS_LEVEL_LETTER(LS_GET_LEVEL(m->flags));
259       *p++ = ' ';
260     }
261
262   /* Time (|stime| + |sutime| + 1 chars) */
263   if (ls->msgfmt & LSFMT_TIME)
264     {
265       const char *q = m->stime;
266       while (*q)
267         *p++ = *q++;
268       if (ls->msgfmt & LSFMT_USEC)
269         {
270           q = m->sutime;
271           while (*q)
272             *p++ = *q++;
273         }
274       *p++ = ' ';
275     }
276
277   /* Process name, PID ( |log_title| + 6 + (|PID|<=10) chars ) */
278   if ((ls->msgfmt & LSFMT_TITLE) && log_title)
279     {
280       if ((ls->msgfmt & LSFMT_PID) && log_pid)
281         p += sprintf(p, "[%s (%d)] ", log_title, log_pid);
282       else
283         p += sprintf(p, "[%s] ", log_title);
284     }
285   else
286     {
287       if ((ls->msgfmt & LSFMT_PID) && log_pid)
288         p += sprintf(p, "[%d] ", log_pid);
289     }
290
291   /* log_stream name ( |ls->name| + 4 chars ) */
292   if (ls->msgfmt & LSFMT_LOGNAME)
293     {
294       if (ls->name)
295         p += sprintf(p, "<%s> ", ls->name);
296       else
297         p += sprintf(p, "<?> ");
298     }
299
300   /* Message type ( |type| + 3 chars ) */
301   if (type)
302     p += sprintf(p, "{%s} ", type);
303
304   /* The message itself ( |m| + 1 chars ) */
305     {
306       const char *q = m->raw_msg;
307       while (*q)
308         *p++ = *q++;
309       *p++ = '\n';
310       *p = '\0';
311       m->m_len = p - m->m;
312       int err = ls->handler(ls, m);
313       if (err)
314         log_report_err(ls, m, err);
315     }
316
317   if (free_buf)
318     xfree(free_buf);
319   return 0;
320 }
321
322 /*** Utility functions ***/
323
324 void
325 msg(unsigned int cat, const char *fmt, ...)
326 {
327   va_list args;
328
329   va_start(args, fmt);
330   vmsg(cat, fmt, args);
331   va_end(args);
332 }
333
334 static void NONRET
335 do_die(void)
336 {
337 #ifdef DEBUG_DIE_BY_ABORT
338   abort();
339 #else
340   exit(1);
341 #endif
342 }
343
344 void
345 die(const char *fmt, ...)
346 {
347   va_list args;
348
349   va_start(args, fmt);
350   vmsg(L_FATAL, fmt, args);
351   va_end(args);
352   if (log_die_hook)
353     log_die_hook();
354   do_die();
355 }
356
357 void
358 assert_failed(const char *assertion, const char *file, int line)
359 {
360   msg(L_FATAL, "Assertion `%s' failed at %s:%d", assertion, file, line);
361   abort();
362 }
363
364 void
365 assert_failed_noinfo(void)
366 {
367   die("Internal error: Assertion failed.");
368 }
369
370 static const char *
371 log_basename(const char *n)
372 {
373   const char *p = n;
374
375   while (*n)
376     if (*n++ == '/')
377       p = n;
378   return p;
379 }
380
381 void
382 log_init(const char *argv0)
383 {
384   if (argv0)
385     {
386       static char log_progname[32];
387       strncpy(log_progname, log_basename(argv0), sizeof(log_progname)-1);
388       log_progname[sizeof(log_progname)-1] = 0;
389       log_title = log_progname;
390     }
391 }
392
393 void
394 log_fork(void)
395 {
396   log_pid = getpid();
397 }
398
399 #ifdef TEST
400
401 #include <syslog.h>
402
403 int main(void)
404 {
405   int type = log_find_type("foo");
406   ASSERT(type < 0);
407   type = log_register_type("foo");
408
409   struct log_stream *ls = log_new_syslog("local3", 0);
410 #if 0
411   log_add_substream(ls, ls);
412   ls->stream_flags |= LSFLAG_ERR_IS_FATAL;
413 #endif
414   msg(L_INFO | ls->regnum, "Brum <%300s>", ":-)");
415   log_set_format(log_default_stream(), ~0U, LSFMT_USEC | LSFMT_TYPE);
416   msg(L_INFO | type, "Brum <%300s>", ":-)");
417   log_close_all();
418   return 0;
419 }
420
421 #endif