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