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 write(2, m->m, m->m_len);
41 struct log_stream log_stream_default = {
44 .handler = default_log_handler,
47 .msgfmt = LSFMT_DEFAULT,
50 .next = (cnode *) &log_stream_default.substreams.head,
51 .prev = (cnode *) &log_stream_default.substreams.head,
55 /*** Registry of streams and their identifiers ***/
57 struct lsbuf_t log_streams; /* A growing array of pointers to log_streams */
58 int log_streams_after = 0; /* The first never-used index in log_streams.ptr */
61 * Find a stream by its identifier given as LS_SET_STRNUM(flags).
62 * Returns NULL if the stream doesn't exist or it's invalid.
64 * If the log-stream machinery has not been initialized (which is normal for programs
65 * with no fancy logging), the log_streams gbuf is empty and this function only
66 * translates stream #0 to the static log_stream_default.
70 log_stream_by_flags(uns flags)
72 int n = LS_GET_STRNUM(flags);
73 if (n < 0 || n >= log_streams_after || log_streams.ptr[n]->regnum == -1)
74 return (n ? NULL : &log_stream_default);
75 return log_streams.ptr[n];
78 /*** Known message types ***/
80 char **log_type_names;
83 log_type_name(uns flags)
85 uns type = LS_GET_TYPE(flags);
87 if (!log_type_names || !log_type_names[type])
90 return log_type_names[type];
96 vmsg(uns cat, const char *fmt, va_list args)
106 uns sighandler = cat & L_SIGHANDLER;
107 struct log_stream *ls;
108 struct log_msg m = { .flags = cat };
110 /* Find the destination stream */
112 ls = &log_stream_default;
113 else if (!(ls = log_stream_by_flags(cat)))
115 msg((LS_CTRL_MASK&cat)|L_WARN, "No log_stream with number %d! Logging to the default log.", LS_GET_STRNUM(cat));
116 ls = &log_stream_default;
119 /* Get the current time */
122 /* CAVEAT: These calls are not safe in signal handlers. */
123 gettimeofday(&tv, NULL);
125 if (localtime_r(&tv.tv_sec, &tm))
129 /* Generate time strings */
132 strftime(stime, sizeof(stime), "%Y-%m-%d %H:%M:%S", &tm);
133 snprintf(sutime, sizeof(sutime), ".%06d", (int)tv.tv_usec);
139 m.stime = "\?\?\?\?-\?\?-\?\? \?\?:\?\?:\?\?";
140 m.sutime = ".\?\?\?\?\?\?";
143 /* Generate the message string */
144 va_copy(args2, args);
145 len = vsnprintf(msgbuf, sizeof(msgbuf), fmt, args2);
147 if (len < (int) sizeof(msgbuf) || sighandler)
151 m.raw_msg = xmalloc(len+1);
152 vsnprintf(m.raw_msg, len+1, fmt, args);
155 /* Remove non-printable characters and newlines */
159 if (*p >= 0 && *p < 0x20 && *p != '\t')
164 /* Pass the message to the log_stream */
165 log_pass_msg(ls, &m);
168 /* Error (such as infinite loop) occurred */
169 log_pass_msg(&log_stream_default, &m);
172 if (m.raw_msg != msgbuf)
177 log_report_err(struct log_stream *ls, struct log_msg *m, int err)
179 if (m->flags & L_LOGGER_ERR)
181 if (ls->stream_flags & LSFLAG_ERR_REPORTED)
183 ls->stream_flags |= LSFLAG_ERR_REPORTED;
185 struct log_msg errm = *m;
187 char *name = (ls->name ? : "<unnamed>");
189 errm.flags = ((ls->stream_flags & LSFLAG_ERR_IS_FATAL) ? L_FATAL : L_ERROR);
190 errm.flags |= L_LOGGER_ERR | (m->flags & LS_CTRL_MASK);
191 errm.raw_msg = errbuf;
193 snprintf(errbuf, sizeof(errbuf), "Error logging to %s: Maximum nesting level of log streams exceeded", name);
197 snprintf(errbuf, sizeof(errbuf), "Error logging to %s: %m", name);
199 log_pass_msg(&log_stream_default, &errm);
201 if (ls->stream_flags & LSFLAG_ERR_IS_FATAL)
205 /* Maximal depth of log_pass_msg recursion */
206 #define LS_MAX_DEPTH 64
209 log_pass_filtered(struct log_stream *ls, struct log_msg *m)
211 /* Pass the message to substreams */
212 CLIST_FOR_EACH(simp_node *, s, ls->substreams)
214 log_pass_msg(s->p, m);
219 /* Will pass to the handler of this stream... is there any? */
223 /* Will print a message type? */
225 if ((ls->msgfmt & LSFMT_TYPE) && LS_GET_TYPE(m->flags))
226 type = log_type_name(m->flags);
228 /* Upper bound on message length */
229 int len = strlen(m->raw_msg) + strlen(m->stime) + strlen(m->sutime) + 32;
231 len += strlen(log_title);
233 len += strlen(ls->name);
235 len += strlen(type) + 3;
237 /* Get a buffer and format the message */
238 char *free_buf = NULL;
239 if (len <= 256 || (m->flags & L_SIGHANDLER))
242 m->m = free_buf = xmalloc(len);
245 /* Level (2 chars) */
246 if (ls->msgfmt & LSFMT_LEVEL)
248 *p++ = LS_LEVEL_LETTER(LS_GET_LEVEL(m->flags));
252 /* Time (|stime| + |sutime| + 1 chars) */
253 if (ls->msgfmt & LSFMT_TIME)
255 const char *q = m->stime;
258 if (ls->msgfmt & LSFMT_USEC)
267 /* Process name, PID ( |log_title| + 6 + (|PID|<=10) chars ) */
268 if ((ls->msgfmt & LSFMT_TITLE) && log_title)
270 if ((ls->msgfmt & LSFMT_PID) && log_pid)
271 p += sprintf(p, "[%s (%d)] ", log_title, log_pid);
273 p += sprintf(p, "[%s] ", log_title);
277 if ((ls->msgfmt & LSFMT_PID) && log_pid)
278 p += sprintf(p, "[%d] ", log_pid);
281 /* log_stream name ( |ls->name| + 4 chars ) */
282 if (ls->msgfmt & LSFMT_LOGNAME)
285 p += sprintf(p, "<%s> ", ls->name);
287 p += sprintf(p, "<?> ");
290 /* Message type ( |type| + 3 chars ) */
292 p += sprintf(p, "{%s} ", type);
294 /* The message itself ( |m| + 1 chars ) */
296 const char *q = m->raw_msg;
302 int err = ls->handler(ls, m);
304 log_report_err(ls, m, err);
312 log_pass_msg(struct log_stream *ls, struct log_msg *m)
316 /* Check recursion depth */
317 if (m->depth > LS_MAX_DEPTH)
319 log_report_err(ls, m, EDEADLK);
324 /* Filter by level and type */
325 if (!((1 << LS_GET_LEVEL(m->flags)) & ls->levels) ||
326 !((1 << LS_GET_TYPE(m->flags)) & ls->types))
331 if (ls->filter && ls->filter(ls, m))
333 // The filter might have called log_pass_filtered()
336 log_pass_filtered(ls, m);
341 /*** Utility functions ***/
344 msg(unsigned int cat, const char *fmt, ...)
349 vmsg(cat, fmt, args);
356 #ifdef DEBUG_DIE_BY_ABORT
359 const char *env = getenv(CONFIG_UCW_ENV_VAR_DIE_BY_ABORT);
367 vdie(const char *fmt, va_list args)
369 vmsg(L_FATAL, fmt, args);
376 die(const char *fmt, ...)
384 assert_failed(const char *assertion, const char *file, int line)
386 msg(L_FATAL, "Assertion `%s' failed at %s:%d", assertion, file, line);
391 assert_failed_msg(const char *assertion, const char *file, int line, const char *fmt, ...)
395 vmsg(L_DEBUG, fmt, args);
396 msg(L_FATAL, "Assertion `%s' failed at %s:%d", assertion, file, line);
401 assert_failed_noinfo(void)
403 die("Internal error: Assertion failed.");
407 log_basename(const char *n)
418 log_init(const char *argv0)
422 static char log_progname[32];
423 strncpy(log_progname, log_basename(argv0), sizeof(log_progname)-1);
424 log_progname[sizeof(log_progname)-1] = 0;
425 log_title = log_progname;
441 int type = log_find_type("foo");
443 type = log_register_type("foo");
445 struct log_stream *ls = log_new_syslog("local3", 0);
447 log_add_substream(ls, ls);
448 ls->stream_flags |= LSFLAG_ERR_IS_FATAL;
450 msg(L_INFO | ls->regnum, "Brum <%300s>", ":-)");
451 log_set_format(log_default_stream(), ~0U, LSFMT_USEC | LSFMT_TYPE);
452 msg(L_INFO | type, "Brum <%300s>", ":-)");