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