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,
48 .substreams.head.next = (cnode *) &log_stream_default.substreams.head,
49 .substreams.head.prev = (cnode *) &log_stream_default.substreams.head,
52 /*** Registry of streams and their identifiers ***/
54 struct lsbuf_t log_streams; /* A growing array of pointers to log_streams */
55 int log_streams_after = 0; /* The first never-used index in log_streams.ptr */
58 * Find a stream by its identifier given as LS_SET_STRNUM(flags).
59 * Returns NULL if the stream doesn't exist or it's invalid.
61 * If the log-stream machinery has not been initialized (which is normal for programs
62 * with no fancy logging), the log_streams gbuf is empty and this function only
63 * translates stream #0 to the static log_stream_default.
67 log_stream_by_flags(uns flags)
69 int n = LS_GET_STRNUM(flags);
70 if (n < 0 || n >= log_streams_after || log_streams.ptr[n]->regnum == -1)
71 return (n ? NULL : &log_stream_default);
72 return log_streams.ptr[n];
75 /*** Known message types ***/
77 char **log_type_names;
80 log_type_name(uns flags)
82 uns type = LS_GET_TYPE(flags);
84 if (!log_type_names || !log_type_names[type])
87 return log_type_names[type];
93 vmsg(uns cat, const char *fmt, va_list args)
103 uns sighandler = cat & L_SIGHANDLER;
104 struct log_stream *ls;
105 struct log_msg m = { .flags = cat };
107 /* Find the destination stream */
109 ls = &log_stream_default;
110 else if (!(ls = log_stream_by_flags(cat)))
112 msg((LS_CTRL_MASK&cat)|L_WARN, "No log_stream with number %d! Logging to the default log.", LS_GET_STRNUM(cat));
113 ls = &log_stream_default;
116 /* Get the current time */
119 /* CAVEAT: These calls are not safe in signal handlers. */
120 gettimeofday(&tv, NULL);
122 if (localtime_r(&tv.tv_sec, &tm))
126 /* Generate time strings */
129 strftime(stime, sizeof(stime), "%Y-%m-%d %H:%M:%S", &tm);
130 snprintf(sutime, sizeof(sutime), ".%06d", (int)tv.tv_usec);
136 m.stime = "\?\?\?\?-\?\?-\?\? \?\?:\?\?:\?\?";
137 m.sutime = ".\?\?\?\?\?\?";
140 /* Generate the message string */
141 va_copy(args2, args);
142 len = vsnprintf(msgbuf, sizeof(msgbuf), fmt, args2);
144 if (len < (int) sizeof(msgbuf) || sighandler)
148 m.raw_msg = xmalloc(len+1);
149 vsnprintf(m.raw_msg, len+1, fmt, args);
152 /* Remove non-printable characters and newlines */
156 if (*p >= 0 && *p < 0x20 && *p != '\t')
161 /* Pass the message to the log_stream */
162 if (log_pass_msg(0, ls, &m))
164 /* Error (such as infinite loop) occurred */
165 log_pass_msg(0, &log_stream_default, &m);
168 if (m.raw_msg != msgbuf)
173 log_report_err(struct log_stream *ls, struct log_msg *m, int err)
175 if (m->flags & L_LOGGER_ERR)
177 if (ls->stream_flags & LSFLAG_ERR_REPORTED)
179 ls->stream_flags |= LSFLAG_ERR_REPORTED;
181 struct log_msg errm = *m;
183 char *name = (ls->name ? : "<unnamed>");
185 errm.flags = ((ls->stream_flags & LSFLAG_ERR_IS_FATAL) ? L_FATAL : L_ERROR);
186 errm.flags |= L_LOGGER_ERR | (m->flags & LS_CTRL_MASK);
187 errm.raw_msg = errbuf;
189 snprintf(errbuf, sizeof(errbuf), "Error logging to %s: Maximum nesting level of log streams exceeded", name);
193 snprintf(errbuf, sizeof(errbuf), "Error logging to %s: %m", name);
195 log_pass_msg(0, &log_stream_default, &errm);
197 if (ls->stream_flags & LSFLAG_ERR_IS_FATAL)
201 /* Maximal depth of log_pass_msg recursion */
202 #define LS_MAX_DEPTH 64
205 log_pass_msg(int depth, struct log_stream *ls, struct log_msg *m)
209 /* Check recursion depth */
210 if (depth > LS_MAX_DEPTH)
212 log_report_err(ls, m, EDEADLK);
216 /* Filter by level, type and hook function */
217 if (!((1 << LS_GET_LEVEL(m->flags)) & ls->levels) ||
218 !((1 << LS_GET_TYPE(m->flags)) & ls->types) ||
219 ls->filter && ls->filter(ls, m))
222 /* Pass the message to substreams */
223 CLIST_FOR_EACH(simp_node *, s, ls->substreams)
224 if (log_pass_msg(depth+1, 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 /*** Utility functions ***/
323 msg(unsigned int cat, const char *fmt, ...)
328 vmsg(cat, fmt, args);
335 #ifdef DEBUG_DIE_BY_ABORT
343 die(const char *fmt, ...)
348 vmsg(L_FATAL, fmt, args);
356 assert_failed(const char *assertion, const char *file, int line)
358 msg(L_FATAL, "Assertion `%s' failed at %s:%d", assertion, file, line);
363 assert_failed_noinfo(void)
365 die("Internal error: Assertion failed.");
369 log_basename(const char *n)
380 log_init(const char *argv0)
384 static char log_progname[32];
385 strncpy(log_progname, log_basename(argv0), sizeof(log_progname)-1);
386 log_progname[sizeof(log_progname)-1] = 0;
387 log_title = log_progname;
403 int type = log_find_type("foo");
405 type = log_register_type("foo");
407 struct log_stream *ls = log_new_syslog("local3", 0);
409 log_add_substream(ls, ls);
410 ls->stream_flags |= LSFLAG_ERR_IS_FATAL;
412 msg(L_INFO | ls->regnum, "Brum <%300s>", ":-)");
413 log_set_format(log_default_stream(), ~0U, LSFMT_USEC | LSFMT_TYPE);
414 msg(L_INFO | type, "Brum <%300s>", ":-)");