]> mj.ucw.cz Git - libucw.git/blob - ucw/log-syslog.c
dc1df456504687e35e5221e00d22a00a240e4927
[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 /* Destructor */
17 static void
18 syslog_close(struct log_stream *ls)
19 {
20   if (ls->name)
21     xfree(ls->name);
22 }
23
24 /* convert severity level to syslog constants */
25 static int
26 syslog_level(int level)
27 {
28   static const int levels[] = {
29     [L_DEBUG] =         LOG_DEBUG,
30     [L_INFO] =          LOG_INFO,
31     [L_INFO_R] =        LOG_INFO,
32     [L_WARN] =          LOG_WARNING,
33     [L_WARN_R] =        LOG_WARNING,
34     [L_ERROR] =         LOG_ERR,
35     [L_ERROR_R] =       LOG_ERR,
36     [L_FATAL] =         LOG_CRIT,
37   };
38   return ((level < (int)ARRAY_SIZE(levels)) ? levels[level] : LOG_NOTICE);
39 }
40
41 /* simple syslog write handler */
42 static int
43 syslog_handler(struct log_stream *ls, struct log_msg *m)
44 {
45   int prio;
46   ASSERT(ls);
47   ASSERT(m);
48
49   // FIXME: Logging of PID
50   prio = syslog_level(LS_GET_LEVEL(m->flags)) | (ls->idata);
51   if (ls->name)
52     syslog(prio | (ls->idata), "%s: %s", ls->name, m->m);
53   else
54     syslog(prio | (ls->idata), "%s", m->m);
55   return 0;
56 }
57
58 /* assign log to a syslog facility */
59 /* initialize with no formatting (syslog adds these inforamtion) */
60 /* name is optional prefix (NULL for none) */
61 struct log_stream *
62 log_new_syslog(int facility, const char *name)
63 {
64   struct log_stream *ls = log_new_stream();
65   if (name)
66     ls->name = xstrdup(name);
67   ls->idata = facility;
68   ls->msgfmt = LSFMT_NONE;
69   ls->handler = syslog_handler;
70   ls->close = syslog_close;
71   return ls;
72 }