2 logger.c -- logging code
3 Copyright (C) 2004-2006 Guus Sliepen <guus@tinc-vpn.org>
4 2004-2005 Ivo Timmermans
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License along
17 with this program; if not, write to the Free Software Foundation, Inc.,
18 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
26 #include "connection.h"
27 #include "control_common.h"
29 debug_t debug_level = DEBUG_NOTHING;
30 static logmode_t logmode = LOGMODE_STDERR;
32 extern char *logfilename;
33 static FILE *logfile = NULL;
35 static HANDLE loghandle = NULL;
37 static const char *logident = NULL;
38 bool logcontrol = false;
40 void openlogger(const char *ident, logmode_t mode) {
50 logfile = fopen(logfilename, "a");
52 fprintf(stderr, "Could not open log file %s: %s\n", logfilename, strerror(errno));
53 logmode = LOGMODE_NULL;
58 loghandle = RegisterEventSource(NULL, logident);
60 fprintf(stderr, "Could not open log handle!");
61 logmode = LOGMODE_NULL;
66 openlog(logident, LOG_CONS | LOG_PID, LOG_DAEMON);
76 if(logmode != LOGMODE_FILE)
80 FILE *newfile = fopen(logfilename, "a");
82 logger(DEBUG_ALWAYS, LOG_ERR, "Unable to reopen log file %s: %s", logfilename, strerror(errno));
89 void logger(int level, int priority, const char *format, ...) {
92 char timestr[32] = "";
93 char message[1024] = "";
95 static bool suppress = false;
97 // Bail out early if there is nothing to do.
101 if(!logcontrol && (level > debug_level || logmode == LOGMODE_NULL))
104 va_start(ap, format);
105 len = vsnprintf(message, sizeof message, format, ap);
108 if(len > 0 && len < sizeof message && message[len - 1] == '\n')
109 message[len - 1] = 0;
111 if(level <= debug_level) {
114 fprintf(stderr, "%s\n", message);
119 strftime(timestr, sizeof timestr, "%Y-%m-%d %H:%M:%S", localtime(&now));
120 fprintf(logfile, "%s %s[%ld]: %s\n", timestr, logident, (long)logpid, message);
126 const char *messages[] = {message};
127 ReportEvent(loghandle, priority, 0, 0, NULL, 1, 0, messages, NULL);
131 syslog(priority, "%s", message);
143 for list_each(connection_t, c, connection_list) {
147 if(level > (c->outcompression >= 0 ? c->outcompression : debug_level))
149 int len = strlen(message);
150 if(send_request(c, "%d %d %d", CONTROL, REQ_LOG, len))
151 send_meta(c, message, len);
157 void closelogger(void) {
164 DeregisterEventSource(loghandle);