2 * UCW Library -- Logging
4 * (c) 1997--2009 Martin Mares <mj@ucw.cz>
5 * (c) 2008 Tomas Gavenciak <gavento@ucw.cz>
6 * (c) 2014 Tomas Valla <tom@ucw.cz>
8 * This software may be freely distributed and used according to the terms
9 * of the GNU Lesser General Public License.
14 #include <ucw/log-internal.h>
15 #include <ucw/simple-lists.h>
28 void (*log_die_hook)(void);
30 static void NONRET do_die(void);
32 /*** The default log stream, which logs to stderr ***/
34 static int default_log_handler(struct log_stream *ls UNUSED, struct log_msg *m)
36 // This is a completely bare version of the log-file module. Errors are ignored.
37 if (write(2, m->m, m->m_len) < 0)
43 struct log_stream log_stream_default = {
46 .handler = default_log_handler,
49 .msgfmt = LSFMT_DEFAULT,
52 .next = (cnode *) &log_stream_default.substreams.head,
53 .prev = (cnode *) &log_stream_default.substreams.head,
57 /*** Registry of streams and their identifiers ***/
59 struct lsbuf_t log_streams; /* A growing array of pointers to log_streams */
60 int log_streams_after = 0; /* The first never-used index in log_streams.ptr */
63 * Find a stream by its identifier given as LS_SET_STRNUM(flags).
64 * Returns NULL if the stream doesn't exist or it's invalid.
66 * If the log-stream machinery has not been initialized (which is normal for programs
67 * with no fancy logging), the log_streams gbuf is empty and this function only
68 * translates stream #0 to the static log_stream_default.
72 log_stream_by_flags(uns flags)
74 int n = LS_GET_STRNUM(flags);
75 if (n < 0 || n >= log_streams_after || log_streams.ptr[n]->regnum == -1)
76 return (n ? NULL : &log_stream_default);
77 return log_streams.ptr[n];
80 /*** Known message types ***/
82 char **log_type_names;
85 log_type_name(uns flags)
87 uns type = LS_GET_TYPE(flags);
89 if (!log_type_names || !log_type_names[type])
92 return log_type_names[type];
98 vmsg(uns cat, const char *fmt, va_list args)
108 uns sighandler = cat & L_SIGHANDLER;
109 struct log_stream *ls;
110 struct log_msg m = { .flags = cat };
112 /* Find the destination stream */
114 ls = &log_stream_default;
115 else if (!(ls = log_stream_by_flags(cat)))
117 msg((LS_CTRL_MASK&cat)|L_WARN, "No log_stream with number %d! Logging to the default log.", LS_GET_STRNUM(cat));
118 ls = &log_stream_default;
121 /* Get the current time */
124 /* CAVEAT: These calls are not safe in signal handlers. */
125 gettimeofday(&tv, NULL);
127 if (localtime_r(&tv.tv_sec, &tm))
131 /* Generate time strings */
134 strftime(stime, sizeof(stime), "%Y-%m-%d %H:%M:%S", &tm);
135 snprintf(sutime, sizeof(sutime), ".%06d", (int)tv.tv_usec);
141 m.stime = "\?\?\?\?-\?\?-\?\? \?\?:\?\?:\?\?";
142 m.sutime = ".\?\?\?\?\?\?";
145 /* Generate the message string */
146 va_copy(args2, args);
147 len = vsnprintf(msgbuf, sizeof(msgbuf), fmt, args2);
149 if (len < (int) sizeof(msgbuf) || sighandler)
153 m.raw_msg = xmalloc(len+1);
154 vsnprintf(m.raw_msg, len+1, fmt, args);
157 /* Remove non-printable characters and newlines */
161 if (*p >= 0 && *p < 0x20 && *p != '\t')
166 /* Pass the message to the log_stream */
167 log_pass_msg(ls, &m);
170 /* Error (such as infinite loop) occurred */
171 log_pass_msg(&log_stream_default, &m);
174 if (m.raw_msg != msgbuf)
179 log_report_err(struct log_stream *ls, struct log_msg *m, int err)
181 if (m->flags & L_LOGGER_ERR)
183 if (ls->stream_flags & LSFLAG_ERR_REPORTED)
185 ls->stream_flags |= LSFLAG_ERR_REPORTED;
187 struct log_msg errm = *m;
189 char *name = (ls->name ? : "<unnamed>");
191 errm.flags = ((ls->stream_flags & LSFLAG_ERR_IS_FATAL) ? L_FATAL : L_ERROR);
192 errm.flags |= L_LOGGER_ERR | (m->flags & LS_CTRL_MASK);
193 errm.raw_msg = errbuf;
195 snprintf(errbuf, sizeof(errbuf), "Error logging to %s: Maximum nesting level of log streams exceeded", name);
199 snprintf(errbuf, sizeof(errbuf), "Error logging to %s: %m", name);
201 log_pass_msg(&log_stream_default, &errm);
203 if (ls->stream_flags & LSFLAG_ERR_IS_FATAL)
207 /* Maximal depth of log_pass_msg recursion */
208 #define LS_MAX_DEPTH 64
211 log_pass_filtered(struct log_stream *ls, struct log_msg *m)
213 /* Pass the message to substreams */
214 CLIST_FOR_EACH(simp_node *, s, ls->substreams)
216 log_pass_msg(s->p, m);
221 /* Will pass to the handler of this stream... is there any? */
225 /* Will print a message type? */
227 if ((ls->msgfmt & LSFMT_TYPE) && LS_GET_TYPE(m->flags))
228 type = log_type_name(m->flags);
230 /* Upper bound on message length */
231 int len = strlen(m->raw_msg) + strlen(m->stime) + strlen(m->sutime) + 32;
233 len += strlen(log_title);
235 len += strlen(ls->name);
237 len += strlen(type) + 3;
239 /* Get a buffer and format the message */
240 char *free_buf = NULL;
241 if (len <= 256 || (m->flags & L_SIGHANDLER))
244 m->m = free_buf = xmalloc(len);
247 /* Level (2 chars) */
248 if (ls->msgfmt & LSFMT_LEVEL)
250 *p++ = LS_LEVEL_LETTER(LS_GET_LEVEL(m->flags));
254 /* Time (|stime| + |sutime| + 1 chars) */
255 if (ls->msgfmt & LSFMT_TIME)
257 const char *q = m->stime;
260 if (ls->msgfmt & LSFMT_USEC)
269 /* Process name, PID ( |log_title| + 6 + (|PID|<=10) chars ) */
270 if ((ls->msgfmt & LSFMT_TITLE) && log_title)
272 if ((ls->msgfmt & LSFMT_PID) && log_pid)
273 p += sprintf(p, "[%s (%d)] ", log_title, log_pid);
275 p += sprintf(p, "[%s] ", log_title);
279 if ((ls->msgfmt & LSFMT_PID) && log_pid)
280 p += sprintf(p, "[%d] ", log_pid);
283 /* log_stream name ( |ls->name| + 4 chars ) */
284 if (ls->msgfmt & LSFMT_LOGNAME)
287 p += sprintf(p, "<%s> ", ls->name);
289 p += sprintf(p, "<?> ");
292 /* Message type ( |type| + 3 chars ) */
294 p += sprintf(p, "{%s} ", type);
296 /* The message itself ( |m| + 1 chars ) */
298 const char *q = m->raw_msg;
304 int err = ls->handler(ls, m);
306 log_report_err(ls, m, err);
314 log_pass_msg(struct log_stream *ls, struct log_msg *m)
318 /* Check recursion depth */
319 if (m->depth > LS_MAX_DEPTH)
321 log_report_err(ls, m, EDEADLK);
326 /* Filter by level and type */
327 if (!((1 << LS_GET_LEVEL(m->flags)) & ls->levels) ||
328 !((1 << LS_GET_TYPE(m->flags)) & ls->types))
333 if (ls->filter && ls->filter(ls, m))
335 // The filter might have called log_pass_filtered()
338 log_pass_filtered(ls, m);
343 /*** Utility functions ***/
346 msg(unsigned int cat, const char *fmt, ...)
351 vmsg(cat, fmt, args);
358 #ifdef DEBUG_DIE_BY_ABORT
361 const char *env = getenv(CONFIG_UCW_ENV_VAR_DIE_BY_ABORT);
369 vdie(const char *fmt, va_list args)
371 vmsg(L_FATAL, fmt, args);
378 die(const char *fmt, ...)
386 assert_failed(const char *assertion, const char *file, int line)
388 msg(L_FATAL, "Assertion `%s' failed at %s:%d", assertion, file, line);
393 assert_failed_msg(const char *assertion, const char *file, int line, const char *fmt, ...)
397 vmsg(L_DEBUG, fmt, args);
398 msg(L_FATAL, "Assertion `%s' failed at %s:%d", assertion, file, line);
403 assert_failed_noinfo(void)
405 die("Internal error: Assertion failed.");
409 log_basename(const char *n)
420 log_init(const char *argv0)
424 static char log_progname[32];
425 strncpy(log_progname, log_basename(argv0), sizeof(log_progname)-1);
426 log_progname[sizeof(log_progname)-1] = 0;
427 log_title = log_progname;
443 int type = log_find_type("foo");
445 type = log_register_type("foo");
447 struct log_stream *ls = log_new_syslog("local3", 0);
449 log_add_substream(ls, ls);
450 ls->stream_flags |= LSFLAG_ERR_IS_FATAL;
452 msg(L_INFO | ls->regnum, "Brum <%300s>", ":-)");
453 log_set_format(log_default_stream(), ~0U, LSFMT_USEC | LSFMT_TYPE);
454 msg(L_INFO | type, "Brum <%300s>", ":-)");