Rewrite log_trace to be thread-safe and some cleanups
This commit is contained in:
78
log_trace.c
78
log_trace.c
@@ -1,64 +1,62 @@
|
||||
#include <time.h>
|
||||
#include <stdio.h>
|
||||
#include <stdarg.h>
|
||||
#include <pthread.h>
|
||||
#include "log_trace.h"
|
||||
#include "confparser.h"
|
||||
|
||||
static FILE *fderr = NULL;
|
||||
static FILE *fdout = NULL;
|
||||
static pthread_once_t once = PTHREAD_ONCE_INIT;
|
||||
static void open_logs(void)
|
||||
|
||||
{
|
||||
if (conf.rmps.errlog)
|
||||
fderr = fopen(conf.rmps.errlog, "a");
|
||||
if (conf.rmps.logfile)
|
||||
fdout = fopen(conf.rmps.logfile, "a");
|
||||
}
|
||||
|
||||
void log_trace(LOG_LEVEL lvl, char *fmt, ... )
|
||||
{
|
||||
LOG_LEVEL cur_lvl = conf.rmps.loglevel - '0';
|
||||
|
||||
if (conf.isvalid)
|
||||
pthread_once(&once, open_logs);
|
||||
if (lvl <= cur_lvl) {
|
||||
va_list list;
|
||||
int fallback = 0;
|
||||
FILE *fd;
|
||||
static const char *prefixes[] = {
|
||||
"ERROR", "WARNING", "INFO", "VERBOSE"
|
||||
};
|
||||
time_t t = time(NULL);
|
||||
struct tm tm = *localtime(&t);
|
||||
if (lvl == ERROR || lvl == WARNING) {
|
||||
fd = fopen(conf.rmps.errlog, "a");
|
||||
if (!fd) {
|
||||
fprintf( stderr,
|
||||
"Failed to append errlog: %s. Redirecting to stderr:\n",
|
||||
conf.rmps.errlog );
|
||||
fd = stderr;
|
||||
fallback = 1;
|
||||
}
|
||||
fprintf( fd,
|
||||
"[%d-%02d-%02d %02d:%02d:%02d] %s: ",
|
||||
tm.tm_year + 1900,
|
||||
tm.tm_mon + 1,
|
||||
tm.tm_mday,
|
||||
tm.tm_hour,
|
||||
tm.tm_min,
|
||||
tm.tm_sec,
|
||||
lvl == ERROR ? "ERROR" : "WARNING" );
|
||||
} else {
|
||||
fd = fopen(conf.rmps.logfile, "a");
|
||||
if (!fd) {
|
||||
fprintf( stderr,
|
||||
"Failed to append logfile: %s. Redirecting to stderr:\n",
|
||||
conf.rmps.logfile );
|
||||
fd = stderr;
|
||||
fallback = 1;
|
||||
}
|
||||
fprintf( fd,
|
||||
"[%d-%02d-%02d %02d:%02d:%02d] %s: ",
|
||||
tm.tm_year + 1900,
|
||||
tm.tm_mon + 1,
|
||||
tm.tm_mday,
|
||||
tm.tm_hour,
|
||||
tm.tm_min,
|
||||
tm.tm_sec,
|
||||
lvl == INFO ? "INFO" : "VERBOSE" );
|
||||
if (lvl == ERROR || lvl == WARNING)
|
||||
fd = fderr;
|
||||
else
|
||||
fd = fdout;
|
||||
if (!fd) {
|
||||
fprintf( stderr,
|
||||
"Failed to append errlog: %s. Redirecting to stderr:\n",
|
||||
conf.rmps.errlog );
|
||||
fd = stderr;
|
||||
}
|
||||
fprintf( fd,
|
||||
"[%d-%02d-%02d %02d:%02d:%02d] %s: ",
|
||||
tm.tm_year + 1900,
|
||||
tm.tm_mon + 1,
|
||||
tm.tm_mday,
|
||||
tm.tm_hour,
|
||||
tm.tm_min,
|
||||
tm.tm_sec,
|
||||
prefixes[lvl-1] );
|
||||
|
||||
va_start(list, fmt);
|
||||
vfprintf(fd, fmt, list);
|
||||
fprintf(fd, "\n");
|
||||
fflush(fd);
|
||||
va_end(list);
|
||||
if (!fallback)
|
||||
fclose(fd);
|
||||
} else
|
||||
return;
|
||||
fflush(stdout);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user