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>
7 * (c) 2020 Pavel Charvat <pchar@ucw.cz>
9 * This software may be freely distributed and used according to the terms
10 * of the GNU Lesser General Public License.
15 #include <ucw/log-internal.h>
16 #include <ucw/simple-lists.h>
29 void (*log_die_hook)(void);
31 static void NONRET do_die(void);
33 /*** The default log stream, which logs to stderr ***/
35 static int default_log_handler(struct log_stream *ls UNUSED, struct log_msg *m)
37 // This is a completely bare version of the log-file module. Errors are ignored.
38 if (write(2, m->m, m->m_len) < 0)
44 struct log_stream log_stream_default = {
47 .handler = default_log_handler,
50 .msgfmt = LSFMT_DEFAULT,
53 .next = (cnode *) &log_stream_default.substreams.head,
54 .prev = (cnode *) &log_stream_default.substreams.head,
58 /*** Registry of streams and their identifiers ***/
60 struct lsbuf_t log_streams; /* A growing array of pointers to log_streams */
61 int log_streams_after = 0; /* The first never-used index in log_streams.ptr */
64 * Find a stream by its identifier given as LS_SET_STRNUM(flags).
65 * Returns NULL if the stream doesn't exist or it's invalid.
67 * If the log-stream machinery has not been initialized (which is normal for programs
68 * with no fancy logging), the log_streams gbuf is empty and this function only
69 * translates stream #0 to the static log_stream_default.
73 log_stream_by_flags(uint flags)
75 int n = LS_GET_STRNUM(flags);
76 if (n < 0 || n >= log_streams_after || log_streams.ptr[n]->regnum == -1)
77 return (n ? NULL : &log_stream_default);
78 return log_streams.ptr[n];
81 /*** Known message types ***/
83 char **log_type_names;
86 log_type_name(uint flags)
88 uint type = LS_GET_TYPE(flags);
90 if (!log_type_names || !log_type_names[type])
93 return log_type_names[type];
99 vmsg(uint cat, const char *fmt, va_list args)
101 int saved_errno = errno;
110 uint sighandler = cat & L_SIGHANDLER;
111 struct log_stream *ls;
112 struct log_msg m = { .flags = cat };
114 /* Find the destination stream */
116 ls = &log_stream_default;
117 else if (!(ls = log_stream_by_flags(cat)))
119 msg((LS_CTRL_MASK&cat)|L_WARN, "No log_stream with number %d! Logging to the default log.", LS_GET_STRNUM(cat));
120 ls = &log_stream_default;
123 /* Get the current time */
126 /* CAVEAT: These calls are not safe in signal handlers. */
127 gettimeofday(&tv, NULL);
129 if (localtime_r(&tv.tv_sec, &tm))
133 /* Generate time strings */
136 strftime(stime, sizeof(stime), "%Y-%m-%d %H:%M:%S", &tm);
137 snprintf(sutime, sizeof(sutime), ".%06d", (int)tv.tv_usec);
143 m.stime = "\?\?\?\?-\?\?-\?\? \?\?:\?\?:\?\?";
144 m.sutime = ".\?\?\?\?\?\?";
147 /* Generate the message string */
148 va_copy(args2, args);
150 len = vsnprintf(msgbuf, sizeof(msgbuf), fmt, args2);
152 if (len < (int) sizeof(msgbuf) || sighandler)
156 m.raw_msg = xmalloc(len+1);
158 vsnprintf(m.raw_msg, len+1, fmt, args);
161 /* Remove non-printable characters and newlines */
165 if (*p >= 0 && *p < 0x20 && *p != '\t')
170 /* Pass the message to the log_stream */
171 log_pass_msg(ls, &m);
174 /* Error (such as infinite loop) occurred */
175 log_pass_msg(&log_stream_default, &m);
178 if (m.raw_msg != msgbuf)
185 log_report_err(struct log_stream *ls, struct log_msg *m, int err)
187 if (m->flags & L_LOGGER_ERR)
189 if (ls->stream_flags & LSFLAG_ERR_REPORTED)
191 ls->stream_flags |= LSFLAG_ERR_REPORTED;
193 struct log_msg errm = *m;
195 char *name = (ls->name ? : "<unnamed>");
197 errm.flags = ((ls->stream_flags & LSFLAG_ERR_IS_FATAL) ? L_FATAL : L_ERROR);
198 errm.flags |= L_LOGGER_ERR | (m->flags & LS_CTRL_MASK);
199 errm.raw_msg = errbuf;
201 snprintf(errbuf, sizeof(errbuf), "Error logging to %s: Maximum nesting level of log streams exceeded", name);
205 snprintf(errbuf, sizeof(errbuf), "Error logging to %s: %m", name);
207 log_pass_msg(&log_stream_default, &errm);
209 if (ls->stream_flags & LSFLAG_ERR_IS_FATAL)
213 /* Maximal depth of log_pass_msg recursion */
214 #define LS_MAX_DEPTH 64
217 log_pass_filtered(struct log_stream *ls, struct log_msg *m)
219 /* Pass the message to substreams */
220 CLIST_FOR_EACH(simp_node *, s, ls->substreams)
222 log_pass_msg(s->p, m);
227 /* Will pass to the handler of this stream... is there any? */
231 /* Will print a message type? */
233 if ((ls->msgfmt & LSFMT_TYPE) && LS_GET_TYPE(m->flags))
234 type = log_type_name(m->flags);
236 /* Upper bound on message length */
237 int len = strlen(m->raw_msg) + strlen(m->stime) + strlen(m->sutime) + 32;
239 len += strlen(log_title);
241 len += strlen(ls->name);
243 len += strlen(type) + 3;
245 /* Get a buffer and format the message */
246 char *free_buf = NULL;
247 if (len <= 256 || (m->flags & L_SIGHANDLER))
250 m->m = free_buf = xmalloc(len);
253 /* Level (2 chars) */
254 if (ls->msgfmt & LSFMT_LEVEL)
256 *p++ = LS_LEVEL_LETTER(LS_GET_LEVEL(m->flags));
260 /* Time (|stime| + |sutime| + 1 chars) */
261 if (ls->msgfmt & LSFMT_TIME)
263 const char *q = m->stime;
266 if (ls->msgfmt & LSFMT_USEC)
275 /* Process name, PID ( |log_title| + 6 + (|PID|<=10) chars ) */
276 if ((ls->msgfmt & LSFMT_TITLE) && log_title)
278 if ((ls->msgfmt & LSFMT_PID) && log_pid)
279 p += sprintf(p, "[%s (%d)] ", log_title, log_pid);
281 p += sprintf(p, "[%s] ", log_title);
285 if ((ls->msgfmt & LSFMT_PID) && log_pid)
286 p += sprintf(p, "[%d] ", log_pid);
289 /* log_stream name ( |ls->name| + 4 chars ) */
290 if (ls->msgfmt & LSFMT_LOGNAME)
293 p += sprintf(p, "<%s> ", ls->name);
295 p += sprintf(p, "<?> ");
298 /* Message type ( |type| + 3 chars ) */
300 p += sprintf(p, "{%s} ", type);
302 /* The message itself ( |m| + 1 chars ) */
304 const char *q = m->raw_msg;
310 int err = ls->handler(ls, m);
312 log_report_err(ls, m, err);
320 log_pass_msg(struct log_stream *ls, struct log_msg *m)
324 /* Check recursion depth */
325 if (m->depth > LS_MAX_DEPTH)
327 log_report_err(ls, m, EDEADLK);
332 /* Filter by level and type */
333 if (!((1 << LS_GET_LEVEL(m->flags)) & ls->levels) ||
334 !((1 << LS_GET_TYPE(m->flags)) & ls->types))
339 if (ls->filter && ls->filter(ls, m))
341 // The filter might have called log_pass_filtered()
344 log_pass_filtered(ls, m);
349 /*** Utility functions ***/
352 msg(uint cat, const char *fmt, ...)
357 vmsg(cat, fmt, args);
364 #ifdef DEBUG_DIE_BY_ABORT
367 const char *env = getenv(CONFIG_UCW_ENV_VAR_DIE_BY_ABORT);
375 vdie(const char *fmt, va_list args)
377 vmsg(L_FATAL, fmt, args);
384 die(const char *fmt, ...)
392 assert_failed(const char *assertion, const char *file, int line)
394 msg(L_FATAL, "Assertion `%s' failed at %s:%d", assertion, file, line);
399 assert_failed_msg(const char *assertion, const char *file, int line, const char *fmt, ...)
403 vmsg(L_DEBUG, fmt, args);
404 msg(L_FATAL, "Assertion `%s' failed at %s:%d", assertion, file, line);
409 assert_failed_noinfo(void)
411 die("Internal error: Assertion failed.");
415 log_basename(const char *n)
426 log_init(const char *argv0)
430 static char log_progname[32];
431 strncpy(log_progname, log_basename(argv0), sizeof(log_progname)-1);
432 log_progname[sizeof(log_progname)-1] = 0;
433 log_title = log_progname;
449 int type = log_find_type("foo");
451 type = log_register_type("foo");
453 struct log_stream *ls = log_new_syslog("local3", 0);
455 log_add_substream(ls, ls);
456 ls->stream_flags |= LSFLAG_ERR_IS_FATAL;
458 msg(L_INFO | ls->regnum, "Brum <%300s>", ":-)");
459 log_set_format(log_default_stream(), ~0U, LSFMT_USEC | LSFMT_TYPE);
460 msg(L_INFO | type, "Brum <%300s>", ":-)");