Issue 22: Convert remaining code to use the log module
[remote/remote-mci.git] / libutil / Log.cc
blob05b4b81985e14bdf731706235ad3cd502460f6a4
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, const 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((FILE *) Log::file, "%s - %s %s\n", strsep(&timestr, "\n"), Log::ident, buf);
73 void
74 Log::fatal(const char *format, ...)
76 va_list params;
78 va_start(params, format);
79 put(Log::FATAL, format, params);
80 va_end(params);
83 void
84 Log::error(const char *format, ...)
86 va_list params;
88 va_start(params, format);
89 put(Log::ERROR, format, params);
90 va_end(params);
93 void
94 Log::warn(const char *format, ...)
96 va_list params;
98 va_start(params, format);
99 put(Log::WARN, format, params);
100 va_end(params);
103 void
104 Log::info(const char *format, ...)
106 va_list params;
108 va_start(params, format);
109 put(Log::INFO, format, params);
110 va_end(params);
113 void
114 Log::debug(const char *format, ...)
116 va_list params;
118 va_start(params, format);
119 put(Log::DEBUG, format, params);
120 va_end(params);
123 const char *Log::ident;
124 const FILE *Log::file;
125 int Log::level;
126 const FILE *Log::SYSLOG = NULL;