1 |
/* |
2 |
slog.C -- logging |
3 |
Copyright (C) 2003 Marc Lehmann <pcg@goof.com> |
4 |
|
5 |
This program is free software; you can redistribute it and/or modify |
6 |
it under the terms of the GNU General Public License as published by |
7 |
the Free Software Foundation; either version 2 of the License, or |
8 |
(at your option) any later version. |
9 |
|
10 |
This program is distributed in the hope that it will be useful, |
11 |
but WITHOUT ANY WARRANTY; without even the implied warranty of |
12 |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
13 |
GNU General Public License for more details. |
14 |
|
15 |
You should have received a copy of the GNU General Public License |
16 |
along with this program; if not, write to the Free Software |
17 |
Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA |
18 |
*/ |
19 |
|
20 |
#include <cstdarg> |
21 |
#include <cstdio> |
22 |
#include <cstring> |
23 |
#include <cstdlib> |
24 |
|
25 |
#include <unistd.h> |
26 |
#include <syslog.h> |
27 |
|
28 |
#include "slog.h" |
29 |
|
30 |
loglevel log_level = L_INFO; |
31 |
const char *log_identity = ""; |
32 |
static int logto = LOGTO_STDERR; |
33 |
|
34 |
loglevel string_to_loglevel (const char *s) |
35 |
{ |
36 |
if (!strcmp (s, "noise")) return L_NOISE; |
37 |
if (!strcmp (s, "trace")) return L_TRACE; |
38 |
if (!strcmp (s, "debug")) return L_DEBUG; |
39 |
if (!strcmp (s, "info")) return L_INFO; |
40 |
if (!strcmp (s, "notice")) return L_NOTICE; |
41 |
if (!strcmp (s, "warn")) return L_WARN; |
42 |
if (!strcmp (s, "error")) return L_ERR; |
43 |
if (!strcmp (s, "critical")) return L_CRIT; |
44 |
|
45 |
return L_NONE; |
46 |
} |
47 |
|
48 |
void log_to (int mask) |
49 |
{ |
50 |
if (logto & LOGTO_SYSLOG) |
51 |
closelog (); |
52 |
|
53 |
logto = mask; |
54 |
|
55 |
if (logto & LOGTO_SYSLOG) |
56 |
openlog (log_identity, LOG_CONS | LOG_PID, LOG_DAEMON); |
57 |
} |
58 |
|
59 |
void slog_ (const loglevel l, const char *m, ...) |
60 |
{ |
61 |
if (l >= log_level) |
62 |
{ |
63 |
va_list ap; |
64 |
va_start (ap, m); |
65 |
char *msg = new char [2048]; |
66 |
|
67 |
vsnprintf (msg, 2048, m, ap); |
68 |
|
69 |
if (logto & LOGTO_SYSLOG) |
70 |
{ |
71 |
int lvl = l == L_TRACE ? LOG_DEBUG |
72 |
: l == L_DEBUG ? LOG_DEBUG |
73 |
: l == L_INFO ? LOG_INFO |
74 |
: l == L_NOTICE ? LOG_NOTICE |
75 |
: l == L_ERR ? LOG_ERR |
76 |
: l == L_CRIT ? LOG_CRIT |
77 |
: LOG_ERR; |
78 |
|
79 |
syslog (lvl, "%s", msg); |
80 |
} |
81 |
|
82 |
if (logto & LOGTO_STDERR) |
83 |
{ |
84 |
write (2, msg, strlen (msg)); |
85 |
write (2, "\n", 1); |
86 |
} |
87 |
|
88 |
delete msg; |
89 |
} |
90 |
} |
91 |
|
92 |
void fatal (const char *m) |
93 |
{ |
94 |
slog (L_CRIT, m); |
95 |
exit (1); |
96 |
} |
97 |
|