Improved --logfile option.

Instead of UNIX time, the log messages now start with the time in RFC3339
format, which human-readable and still easy for the computer to parse and sort.
The HUP signal will also cause the log file to be closed and reopened, which is
useful when log rotation is used. If there is an error while opening the log
file, this is logged to stderr.
This commit is contained in:
Guus Sliepen 2011-06-06 16:26:11 +02:00
parent b3bbeab6e6
commit 4b3fd94b1c
7 changed files with 39 additions and 4 deletions

View file

@ -44,14 +44,18 @@ void openlogger(const char *ident, logmode_t mode) {
case LOGMODE_FILE:
logpid = getpid();
logfile = fopen(logfilename, "a");
if(!logfile)
if(!logfile) {
fprintf(stderr, "Could not open log file %s: %s\n", logfilename, strerror(errno));
logmode = LOGMODE_NULL;
}
break;
case LOGMODE_SYSLOG:
#ifdef HAVE_MINGW
loghandle = RegisterEventSource(NULL, logident);
if(!loghandle)
if(!loghandle) {
fprintf(stderr, "Could not open log handle!");
logmode = LOGMODE_NULL;
}
break;
#else
#ifdef HAVE_SYSLOG_H
@ -64,8 +68,24 @@ void openlogger(const char *ident, logmode_t mode) {
}
}
void reopenlogger() {
if(logmode != LOGMODE_FILE)
return;
fflush(logfile);
FILE *newfile = fopen(logfilename, "a");
if(!newfile) {
logger(LOG_ERR, "Unable to reopen log file %s: %s\n", logfilename, strerror(errno));
return;
}
fclose(logfile);
logfile = newfile;
}
void logger(int priority, const char *format, ...) {
va_list ap;
char timestr[32] = "";
time_t now;
va_start(ap, format);
@ -76,7 +96,9 @@ void logger(int priority, const char *format, ...) {
fflush(stderr);
break;
case LOGMODE_FILE:
fprintf(logfile, "%ld %s[%ld]: ", time(NULL), logident, (long)logpid);
now = time(NULL);
strftime(timestr, sizeof timestr, "%Y-%m-%d %H:%M:%S", localtime(&now));
fprintf(logfile, "%s %s[%ld]: ", timestr, logident, (long)logpid);
vfprintf(logfile, format, ap);
fprintf(logfile, "\n");
fflush(logfile);

View file

@ -47,6 +47,7 @@ enum {
extern debug_t debug_level;
extern void openlogger(const char *, logmode_t);
extern void reopenlogger(void);
extern void logger(int, const char *, ...) __attribute__ ((__format__(printf, 2, 3)));
extern void closelogger(void);

View file

@ -501,6 +501,8 @@ int main_loop(void) {
struct stat s;
sighup = false;
reopenlogger();
/* Reread our own configuration file */