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,
49 .next = (cnode *) &log_stream_default.substreams.head,
50 .prev = (cnode *) &log_stream_default.substreams.head,
54 /*** Registry of streams and their identifiers ***/
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 */
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.
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.
69 log_stream_by_flags(uns flags)
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];
77 /*** Known message types ***/
79 char **log_type_names;
82 log_type_name(uns flags)
84 uns type = LS_GET_TYPE(flags);
86 if (!log_type_names || !log_type_names[type])
89 return log_type_names[type];
95 vmsg(uns cat, const char *fmt, va_list args)
105 uns sighandler = cat & L_SIGHANDLER;
106 struct log_stream *ls;
107 struct log_msg m = { .flags = cat };
109 /* Find the destination stream */
111 ls = &log_stream_default;
112 else if (!(ls = log_stream_by_flags(cat)))
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;
118 /* Get the current time */
121 /* CAVEAT: These calls are not safe in signal handlers. */
122 gettimeofday(&tv, NULL);
124 if (localtime_r(&tv.tv_sec, &tm))
128 /* Generate time strings */
131 strftime(stime, sizeof(stime), "%Y-%m-%d %H:%M:%S", &tm);
132 snprintf(sutime, sizeof(sutime), ".%06d", (int)tv.tv_usec);
138 m.stime = "\?\?\?\?-\?\?-\?\? \?\?:\?\?:\?\?";
139 m.sutime = ".\?\?\?\?\?\?";
142 /* Generate the message string */
143 va_copy(args2, args);
144 len = vsnprintf(msgbuf, sizeof(msgbuf), fmt, args2);
146 if (len < (int) sizeof(msgbuf) || sighandler)
150 m.raw_msg = xmalloc(len+1);
151 vsnprintf(m.raw_msg, len+1, fmt, args);
154 /* Remove non-printable characters and newlines */
158 if (*p >= 0 && *p < 0x20 && *p != '\t')
163 /* Pass the message to the log_stream */
164 log_pass_msg(ls, &m);
167 /* Error (such as infinite loop) occurred */
168 log_pass_msg(&log_stream_default, &m);
171 if (m.raw_msg != msgbuf)
176 log_report_err(struct log_stream *ls, struct log_msg *m, int err)
178 if (m->flags & L_LOGGER_ERR)
180 if (ls->stream_flags & LSFLAG_ERR_REPORTED)
182 ls->stream_flags |= LSFLAG_ERR_REPORTED;
184 struct log_msg errm = *m;
186 char *name = (ls->name ? : "<unnamed>");
188 errm.flags = ((ls->stream_flags & LSFLAG_ERR_IS_FATAL) ? L_FATAL : L_ERROR);
189 errm.flags |= L_LOGGER_ERR | (m->flags & LS_CTRL_MASK);
190 errm.raw_msg = errbuf;
192 snprintf(errbuf, sizeof(errbuf), "Error logging to %s: Maximum nesting level of log streams exceeded", name);
196 snprintf(errbuf, sizeof(errbuf), "Error logging to %s: %m", name);
198 log_pass_msg(&log_stream_default, &errm);
200 if (ls->stream_flags & LSFLAG_ERR_IS_FATAL)
204 /* Maximal depth of log_pass_msg recursion */
205 #define LS_MAX_DEPTH 64
208 log_pass_filtered(struct log_stream *ls, struct log_msg *m)
210 /* Pass the message to substreams */
211 CLIST_FOR_EACH(simp_node *, s, ls->substreams)
213 log_pass_msg(s->p, m);
218 /* Will pass to the handler of this stream... is there any? */
222 /* Will print a message type? */
224 if ((ls->msgfmt & LSFMT_TYPE) && LS_GET_TYPE(m->flags))
225 type = log_type_name(m->flags);
227 /* Upper bound on message length */
228 int len = strlen(m->raw_msg) + strlen(m->stime) + strlen(m->sutime) + 32;
230 len += strlen(log_title);
232 len += strlen(ls->name);
234 len += strlen(type) + 3;
236 /* Get a buffer and format the message */
237 char *free_buf = NULL;
238 if (len <= 256 || (m->flags & L_SIGHANDLER))
241 m->m = free_buf = xmalloc(len);
244 /* Level (2 chars) */
245 if (ls->msgfmt & LSFMT_LEVEL)
247 *p++ = LS_LEVEL_LETTER(LS_GET_LEVEL(m->flags));
251 /* Time (|stime| + |sutime| + 1 chars) */
252 if (ls->msgfmt & LSFMT_TIME)
254 const char *q = m->stime;
257 if (ls->msgfmt & LSFMT_USEC)
266 /* Process name, PID ( |log_title| + 6 + (|PID|<=10) chars ) */
267 if ((ls->msgfmt & LSFMT_TITLE) && log_title)
269 if ((ls->msgfmt & LSFMT_PID) && log_pid)
270 p += sprintf(p, "[%s (%d)] ", log_title, log_pid);
272 p += sprintf(p, "[%s] ", log_title);
276 if ((ls->msgfmt & LSFMT_PID) && log_pid)
277 p += sprintf(p, "[%d] ", log_pid);
280 /* log_stream name ( |ls->name| + 4 chars ) */
281 if (ls->msgfmt & LSFMT_LOGNAME)
284 p += sprintf(p, "<%s> ", ls->name);
286 p += sprintf(p, "<?> ");
289 /* Message type ( |type| + 3 chars ) */
291 p += sprintf(p, "{%s} ", type);
293 /* The message itself ( |m| + 1 chars ) */
295 const char *q = m->raw_msg;
301 int err = ls->handler(ls, m);
303 log_report_err(ls, m, err);
311 log_pass_msg(struct log_stream *ls, struct log_msg *m)
315 /* Check recursion depth */
316 if (m->depth > LS_MAX_DEPTH)
318 log_report_err(ls, m, EDEADLK);
323 /* Filter by level and type */
324 if (!((1 << LS_GET_LEVEL(m->flags)) & ls->levels) ||
325 !((1 << LS_GET_TYPE(m->flags)) & ls->types))
330 if (ls->filter && ls->filter(ls, m))
332 // The filter might have called log_pass_filtered()
335 log_pass_filtered(ls, m);
340 /*** Utility functions ***/
343 msg(unsigned int cat, const char *fmt, ...)
348 vmsg(cat, fmt, args);
355 #ifdef DEBUG_DIE_BY_ABORT
358 const char *env = getenv(CONFIG_UCW_ENV_VAR_DIE_BY_ABORT);
366 vdie(const char *fmt, va_list args)
368 vmsg(L_FATAL, fmt, args);
375 die(const char *fmt, ...)
383 assert_failed(const char *assertion, const char *file, int line)
385 msg(L_FATAL, "Assertion `%s' failed at %s:%d", assertion, file, line);
390 assert_failed_noinfo(void)
392 die("Internal error: Assertion failed.");
396 log_basename(const char *n)
407 log_init(const char *argv0)
411 static char log_progname[32];
412 strncpy(log_progname, log_basename(argv0), sizeof(log_progname)-1);
413 log_progname[sizeof(log_progname)-1] = 0;
414 log_title = log_progname;
430 int type = log_find_type("foo");
432 type = log_register_type("foo");
434 struct log_stream *ls = log_new_syslog("local3", 0);
436 log_add_substream(ls, ls);
437 ls->stream_flags |= LSFLAG_ERR_IS_FATAL;
439 msg(L_INFO | ls->regnum, "Brum <%300s>", ":-)");
440 log_set_format(log_default_stream(), ~0U, LSFMT_USEC | LSFMT_TYPE);
441 msg(L_INFO | type, "Brum <%300s>", ":-)");