Files
rmps/src/log.c
2019-01-09 23:58:59 +02:00

101 lines
2.2 KiB
C

/*
* log.c
*
* Copyright (C) 2018 by Bogomil Vasilev <b.vasilev@smirky.net>
*
* This file is part of Remote Management and Provisioning System (RMPS).
*
* RMPS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* RMPS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with RMPS. If not, see <http://www.gnu.org/licenses/>.
*/
#include <time.h>
#include <stdio.h>
#include <stdarg.h>
#include <pthread.h>
#include <openssl/err.h>
#include "log.h"
#include "confparser.h"
static FILE *fderr;
static FILE *fdout;
static pthread_once_t once = PTHREAD_ONCE_INIT;
static pthread_once_t init_once = PTHREAD_ONCE_INIT;
static void open_logs(void)
{
fderr = fopen(conf.rmps.errlog, "a");
if (fderr == NULL)
fderr = stderr;
else
setvbuf(fderr, NULL, _IOLBF, 0);
fdout = fopen(conf.rmps.logfile, "a");
if (fdout == NULL)
fdout = stdout;
else
setvbuf(fdout, NULL, _IOLBF, 0);
}
void log_ssl(void)
{
ERR_print_errors_fp(fderr);
fflush(fderr);
}
static void set_fpts(void)
{
fderr = stderr;
fdout = stdout;
}
void log(enum LOG_LEVEL lvl, char *fmt, ...)
{
char fmt_with_pfx[1024];
pthread_once(&init_once, set_fpts);
if (conf.isvalid)
pthread_once(&once, open_logs);
if (lvl <= conf.rmps.loglevel) {
va_list list;
FILE *fp;
static const char * const prefixes[] = {
"ERROR", "WARNING", "INFO", "VERBOSE"
};
time_t t = time(NULL);
struct tm tm;
localtime_r(&t, &tm);
if (lvl == ERROR || lvl == WARNING)
fp = fderr;
else
fp = fdout;
snprintf(fmt_with_pfx,
sizeof(fmt_with_pfx),
"[%d-%02d-%02d %02d:%02d:%02d] %s: %s\n",
tm.tm_year + 1900,
tm.tm_mon + 1,
tm.tm_mday,
tm.tm_hour,
tm.tm_min,
tm.tm_sec,
prefixes[lvl-1],
fmt);
va_start(list, fmt);
vfprintf(fp, fmt_with_pfx, list);
va_end(list);
}
}