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 if (log_pass_msg(0, ls, &m))
166 /* Error (such as infinite loop) occurred */
167 log_pass_msg(0, &log_stream_default, &m);
170 if (m.raw_msg != msgbuf)
175 log_report_err(struct log_stream *ls, struct log_msg *m, int err)
177 if (m->flags & L_LOGGER_ERR)
179 if (ls->stream_flags & LSFLAG_ERR_REPORTED)
181 ls->stream_flags |= LSFLAG_ERR_REPORTED;
183 struct log_msg errm = *m;
185 char *name = (ls->name ? : "<unnamed>");
187 errm.flags = ((ls->stream_flags & LSFLAG_ERR_IS_FATAL) ? L_FATAL : L_ERROR);
188 errm.flags |= L_LOGGER_ERR | (m->flags & LS_CTRL_MASK);
189 errm.raw_msg = errbuf;
191 snprintf(errbuf, sizeof(errbuf), "Error logging to %s: Maximum nesting level of log streams exceeded", name);
195 snprintf(errbuf, sizeof(errbuf), "Error logging to %s: %m", name);
197 log_pass_msg(0, &log_stream_default, &errm);
199 if (ls->stream_flags & LSFLAG_ERR_IS_FATAL)
203 /* Maximal depth of log_pass_msg recursion */
204 #define LS_MAX_DEPTH 64
207 log_pass_msg(int depth, struct log_stream *ls, struct log_msg *m)
211 /* Check recursion depth */
212 if (depth > LS_MAX_DEPTH)
214 log_report_err(ls, m, EDEADLK);
218 /* Filter by level, type and hook function */
219 if (!((1 << LS_GET_LEVEL(m->flags)) & ls->levels) ||
220 !((1 << LS_GET_TYPE(m->flags)) & ls->types) ||
221 ls->filter && ls->filter(ls, m))
224 /* Pass the message to substreams */
225 CLIST_FOR_EACH(simp_node *, s, ls->substreams)
226 if (log_pass_msg(depth+1, s->p, m))
229 /* Will pass to the handler of this stream... is there any? */
233 /* Will print a message type? */
235 if ((ls->msgfmt & LSFMT_TYPE) && LS_GET_TYPE(m->flags))
236 type = log_type_name(m->flags);
238 /* Upper bound on message length */
239 int len = strlen(m->raw_msg) + strlen(m->stime) + strlen(m->sutime) + 32;
241 len += strlen(log_title);
243 len += strlen(ls->name);
245 len += strlen(type) + 3;
247 /* Get a buffer and format the message */
248 char *free_buf = NULL;
249 if (len <= 256 || (m->flags & L_SIGHANDLER))
252 m->m = free_buf = xmalloc(len);
255 /* Level (2 chars) */
256 if (ls->msgfmt & LSFMT_LEVEL)
258 *p++ = LS_LEVEL_LETTER(LS_GET_LEVEL(m->flags));
262 /* Time (|stime| + |sutime| + 1 chars) */
263 if (ls->msgfmt & LSFMT_TIME)
265 const char *q = m->stime;
268 if (ls->msgfmt & LSFMT_USEC)
277 /* Process name, PID ( |log_title| + 6 + (|PID|<=10) chars ) */
278 if ((ls->msgfmt & LSFMT_TITLE) && log_title)
280 if ((ls->msgfmt & LSFMT_PID) && log_pid)
281 p += sprintf(p, "[%s (%d)] ", log_title, log_pid);
283 p += sprintf(p, "[%s] ", log_title);
287 if ((ls->msgfmt & LSFMT_PID) && log_pid)
288 p += sprintf(p, "[%d] ", log_pid);
291 /* log_stream name ( |ls->name| + 4 chars ) */
292 if (ls->msgfmt & LSFMT_LOGNAME)
295 p += sprintf(p, "<%s> ", ls->name);
297 p += sprintf(p, "<?> ");
300 /* Message type ( |type| + 3 chars ) */
302 p += sprintf(p, "{%s} ", type);
304 /* The message itself ( |m| + 1 chars ) */
306 const char *q = m->raw_msg;
312 int err = ls->handler(ls, m);
314 log_report_err(ls, m, err);
322 /*** Utility functions ***/
325 msg(unsigned int cat, const char *fmt, ...)
330 vmsg(cat, fmt, args);
337 #ifdef DEBUG_DIE_BY_ABORT
345 die(const char *fmt, ...)
350 vmsg(L_FATAL, fmt, args);
358 assert_failed(const char *assertion, const char *file, int line)
360 msg(L_FATAL, "Assertion `%s' failed at %s:%d", assertion, file, line);
365 assert_failed_noinfo(void)
367 die("Internal error: Assertion failed.");
371 log_basename(const char *n)
382 log_init(const char *argv0)
386 static char log_progname[32];
387 strncpy(log_progname, log_basename(argv0), sizeof(log_progname)-1);
388 log_progname[sizeof(log_progname)-1] = 0;
389 log_title = log_progname;
405 int type = log_find_type("foo");
407 type = log_register_type("foo");
409 struct log_stream *ls = log_new_syslog("local3", 0);
411 log_add_substream(ls, ls);
412 ls->stream_flags |= LSFLAG_ERR_IS_FATAL;
414 msg(L_INFO | ls->regnum, "Brum <%300s>", ":-)");
415 log_set_format(log_default_stream(), ~0U, LSFMT_USEC | LSFMT_TYPE);
416 msg(L_INFO | type, "Brum <%300s>", ":-)");