]> mj.ucw.cz Git - libucw.git/blob - ucw/log-syslog.c
Logging: Documentation and minor cleanups of headers.
[libucw.git] / ucw / log-syslog.c
1 /*
2  *      UCW Library -- Logging to Syslog
3  *
4  *      (c) 2009 Martin Mares <mj@ucw.cz>
5  *      (c) 2008 Tomas Gavenciak <gavento@ucw.cz>
6  *
7  *      This software may be freely distributed and used according to the terms
8  *      of the GNU Lesser General Public License.
9  */
10
11 #include "ucw/lib.h"
12 #include "ucw/log.h"
13
14 #include <syslog.h>
15
16 struct syslog_stream {
17   struct log_stream ls;
18   int facility;
19 };
20
21 /* Destructor */
22 static void
23 syslog_close(struct log_stream *ls)
24 {
25   if (ls->name)
26     xfree(ls->name);
27 }
28
29 /* convert severity level to syslog constants */
30 static int
31 syslog_level(int level)
32 {
33   static const int levels[] = {
34     [L_DEBUG] =         LOG_DEBUG,
35     [L_INFO] =          LOG_INFO,
36     [L_INFO_R] =        LOG_INFO,
37     [L_WARN] =          LOG_WARNING,
38     [L_WARN_R] =        LOG_WARNING,
39     [L_ERROR] =         LOG_ERR,
40     [L_ERROR_R] =       LOG_ERR,
41     [L_FATAL] =         LOG_CRIT,
42   };
43   return ((level < (int)ARRAY_SIZE(levels)) ? levels[level] : LOG_NOTICE);
44 }
45
46 /* simple syslog write handler */
47 static int
48 syslog_handler(struct log_stream *ls, struct log_msg *m)
49 {
50   struct syslog_stream *ss = (struct syslog_stream *) ls;
51   int prio;
52   ASSERT(ls);
53   ASSERT(m);
54
55   // FIXME: Logging of PID
56   prio = syslog_level(LS_GET_LEVEL(m->flags)) | ss->facility;
57   if (ls->name)
58     syslog(prio, "%s: %s", ls->name, m->m);
59   else
60     syslog(prio, "%s", m->m);
61   return 0;
62 }
63
64 /* assign log to a syslog facility */
65 /* initialize with no formatting (syslog adds these inforamtion) */
66 /* name is optional prefix (NULL for none) */
67 struct log_stream *
68 log_new_syslog(int facility, const char *name)
69 {
70   struct log_stream *ls = log_new_stream(sizeof(struct syslog_stream));
71   struct syslog_stream *ss = (struct syslog_stream *) ls;
72   if (name)
73     ls->name = xstrdup(name);
74   ls->msgfmt = 0;
75   ls->handler = syslog_handler;
76   ls->close = syslog_close;
77   ss->facility = facility;
78   return ls;
79   // FIXME: L_SIGHANDLER?
80 }