2 * UCW Library -- Logging
4 * (c) 1997--2009 Martin Mares <mj@ucw.cz>
5 * (c) 2008 Tomas Gavenciak <gavento@ucw.cz>
7 * This software may be freely distributed and used according to the terms
8 * of the GNU Lesser General Public License.
13 #include "ucw/log-internal.h"
14 #include "ucw/simple-lists.h"
27 void (*log_die_hook)(void);
29 static void NONRET do_die(void);
31 /*** The default log stream, which logs to stderr ***/
33 static int default_log_handler(struct log_stream *ls UNUSED, struct log_msg *m)
35 // This is a completely bare version of the log-file module. Errors are ignored.
36 write(2, m->m, m->m_len);
40 struct log_stream log_stream_default = {
43 .handler = default_log_handler,
46 .msgfmt = LSFMT_DEFAULT,
48 .substreams.head.next = (cnode *) &log_stream_default.substreams.head,
49 .substreams.head.prev = (cnode *) &log_stream_default.substreams.head,
52 /*** Registry of streams and their identifiers ***/
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 */
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.
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.
67 log_stream_by_flags(uns flags)
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];
75 /*** Known message types ***/
77 char **log_type_names;
80 log_type_name(uns flags)
82 uns type = LS_GET_TYPE(flags);
84 if (!log_type_names || !log_type_names[type])
87 return log_type_names[type];
93 vmsg(uns cat, const char *fmt, va_list args)
103 uns sighandler = cat & L_SIGHANDLER;
104 struct log_stream *ls;
105 struct log_msg m = { .flags = cat };
107 /* Find the destination stream */
109 ls = &log_stream_default;
110 else if (!(ls = log_stream_by_flags(cat)))
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;
116 /* Get the current time */
119 /* CAVEAT: These calls are not safe in signal handlers. */
120 gettimeofday(&tv, NULL);
121 if (localtime_r(&tv.tv_sec, &tm))
125 /* Generate time strings */
128 strftime(stime, sizeof(stime), "%Y-%m-%d %H:%M:%S", &tm);
129 snprintf(sutime, sizeof(sutime), ".%06d", (int)tv.tv_usec);
135 m.stime = "\?\?\?\?-\?\?-\?\? \?\?:\?\?:\?\?";
136 m.sutime = ".\?\?\?\?\?\?";
139 /* Generate the message string */
140 va_copy(args2, args);
141 len = vsnprintf(msgbuf, sizeof(msgbuf), fmt, args2);
143 if (len < (int) sizeof(msgbuf) || sighandler)
147 m.raw_msg = xmalloc(len+1);
148 vsnprintf(m.raw_msg, len+1, fmt, args);
151 /* Remove non-printable characters and newlines */
155 if (*p < 0x20 && *p != '\t')
160 /* Pass the message to the log_stream */
161 if (log_pass_msg(0, ls, &m))
163 /* Error (such as infinite loop) occurred */
164 log_pass_msg(0, &log_stream_default, &m);
167 if (m.raw_msg != msgbuf)
172 log_report_err(struct log_stream *ls, struct log_msg *m, int err)
174 if (m->flags & L_LOGGER_ERR)
176 if (ls->stream_flags & LSFLAG_ERR_REPORTED)
178 ls->stream_flags |= LSFLAG_ERR_REPORTED;
180 struct log_msg errm = *m;
182 char *name = (ls->name ? : "<unnamed>");
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;
188 snprintf(errbuf, sizeof(errbuf), "Error logging to %s: Maximum nesting level of log streams exceeded", name);
192 snprintf(errbuf, sizeof(errbuf), "Error logging to %s: %m", name);
194 log_pass_msg(0, &log_stream_default, &errm);
196 if (ls->stream_flags & LSFLAG_ERR_IS_FATAL)
200 /* Maximal depth of log_pass_msg recursion */
201 #define LS_MAX_DEPTH 64
204 log_pass_msg(int depth, struct log_stream *ls, struct log_msg *m)
208 /* Check recursion depth */
209 if (depth > LS_MAX_DEPTH)
211 log_report_err(ls, m, EDEADLK);
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))
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))
226 /* Will pass to the handler of this stream... is there any? */
230 /* Will print a message type? */
232 if ((ls->msgfmt & LSFMT_TYPE) && LS_GET_TYPE(m->flags))
233 type = log_type_name(m->flags);
235 /* Upper bound on message length */
236 int len = strlen(m->raw_msg) + strlen(m->stime) + strlen(m->sutime) + 32;
238 len += strlen(log_title);
240 len += strlen(ls->name);
242 len += strlen(type) + 3;
244 /* Get a buffer and format the message */
245 char *free_buf = NULL;
246 if (len <= 256 || (m->flags & L_SIGHANDLER))
249 m->m = free_buf = xmalloc(len);
252 /* Level (2 chars) */
253 if (ls->msgfmt & LSFMT_LEVEL)
255 *p++ = LS_LEVEL_LETTER(LS_GET_LEVEL(m->flags));
259 /* Time (|stime| + |sutime| + 1 chars) */
260 if (ls->msgfmt & LSFMT_TIME)
262 const char *q = m->stime;
265 if (ls->msgfmt & LSFMT_USEC)
274 /* Process name, PID ( |log_title| + 6 + (|PID|<=10) chars ) */
275 if ((ls->msgfmt & LSFMT_TITLE) && log_title)
277 if ((ls->msgfmt & LSFMT_PID) && log_pid)
278 p += sprintf(p, "[%s (%d)] ", log_title, log_pid);
280 p += sprintf(p, "[%s] ", log_title);
284 if ((ls->msgfmt & LSFMT_PID) && log_pid)
285 p += sprintf(p, "[%d] ", log_pid);
288 /* log_stream name ( |ls->name| + 4 chars ) */
289 if (ls->msgfmt & LSFMT_LOGNAME)
292 p += sprintf(p, "<%s> ", ls->name);
294 p += sprintf(p, "<?> ");
297 /* Message type ( |type| + 3 chars ) */
299 p += sprintf(p, "{%s} ", type);
301 /* The message itself ( |m| + 1 chars ) */
303 const char *q = m->raw_msg;
309 int err = ls->handler(ls, m);
311 log_report_err(ls, m, err);
319 /*** Utility functions ***/
322 msg(unsigned int cat, const char *fmt, ...)
327 vmsg(cat, fmt, args);
334 #ifdef DEBUG_DIE_BY_ABORT
342 die(const char *fmt, ...)
347 vmsg(L_FATAL, fmt, args);
355 assert_failed(const char *assertion, const char *file, int line)
357 msg(L_FATAL, "Assertion `%s' failed at %s:%d", assertion, file, line);
362 assert_failed_noinfo(void)
364 die("Internal error: Assertion failed.");
368 log_basename(const char *n)
379 log_init(const char *argv0)
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;
402 int type = log_find_type("foo");
404 type = log_register_type("foo");
406 struct log_stream *ls = log_new_syslog("local3", 0);
408 log_add_substream(ls, ls);
409 ls->stream_flags |= LSFLAG_ERR_IS_FATAL;
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>", ":-)");