MoteHost: Improve error checking when daemonizing
[remote/remote-mci.git] / libutil / Log.cc
blob1bc3c4e745b4c120d5e52a271f0cfd633c76a788
1 /* Put log messages either to stdout or syslog.
3 * Assimilated from git.git::daemon.c on 2007-05-19. */
5 #include <sys/types.h>
6 #include <unistd.h>
7 #include <time.h>
8 #include <string.h>
10 #include "libutil/Log.h"
12 namespace remote { namespace util {
14 void
15 Log::open(const char *ident, int level, FILE *file)
17 if (use_syslog()) {
18 closelog();
21 log_ident = ident;
22 log_level = level;
23 log_file = file;
25 if (use_syslog()) {
26 openlog(log_ident, 0, LOG_DAEMON);
30 void
31 Log::put(int priority, const char *format, va_list params)
33 /* We should do a single write so that it is atomic and output
34 * of several processes do not get intermingled. */
35 char buf[1024];
36 int buflen;
37 int maxlen, msglen;
38 time_t t;
39 char *timestr;
41 if (ignore(priority))
42 return;
44 /* sizeof(buf) should be big enough for "[pid] \n" */
45 buflen = snprintf(buf, sizeof(buf), "[%ld] ", (long) getpid());
47 maxlen = sizeof(buf) - buflen - 1; /* -1 for our own LF */
48 msglen = vsnprintf(buf + buflen, maxlen, format, params);
50 if (use_syslog()) {
51 syslog(priority, "%s", buf);
52 return;
55 /* maxlen counted our own LF but also counts space given to
56 * vsnprintf for the terminating NUL. We want to make sure that
57 * we have space for our own LF and NUL after the "meat" of the
58 * message, so truncate it at maxlen - 1.
60 if (msglen > maxlen - 1)
61 msglen = maxlen - 1;
62 else if (msglen < 0)
63 msglen = 0; /* Protect against weird return values. */
64 buflen += msglen;
66 buf[buflen] = '\0';
68 time(&t);
69 timestr = ctime(&t);
70 fprintf(log_file, "%s - %s %s\n", strsep(&timestr, "\n"), log_ident, buf);
73 void
74 Log::error(const char *format, ...)
76 va_list params;
78 va_start(params, format);
79 put(LOG_ERR, format, params);
80 va_end(params);
83 void
84 Log::warn(const char *format, ...)
86 va_list params;
88 va_start(params, format);
89 put(LOG_WARNING, format, params);
90 va_end(params);
93 void
94 Log::info(const char *format, ...)
96 va_list params;
98 va_start(params, format);
99 put(LOG_INFO, format, params);
100 va_end(params);
103 void
104 Log::debug(const char *format, ...)
106 va_list params;
108 va_start(params, format);
109 put(LOG_DEBUG, format, params);
110 va_end(params);
113 const char *Log::log_ident;
114 FILE *Log::log_file;
115 int Log::log_level;