ccubes-cl/logging.c

127 lines
2.1 KiB
C
Raw Normal View History

2025-03-20 19:32:25 +02:00
/*
* Copyright (c) 2012, Marius Barbu <msb@avengis.com>
* Copyright (c) 2013, Paul Irofti <paul@irofti.net>
*/
#include <stdio.h> /* FILE */
#include <stdlib.h> /* abort */
#include <stdarg.h>
#include <string.h> /* strrchr */
#include "tree.h"
#include "config.h"
#include "logging.h"
static char *levelName[] = {
"INFO",
"DEBUG",
"WARN",
"ERROR"
};
static FILE *logFile;
static char*
nice_path(char *name)
{
if (strrchr(name, '/')) {
name = strrchr(name, '/') + 1;
} else if (strrchr(name, '\\')) {
name = strrchr(name, '\\') + 1;
}
return name;
}
enum LogLevel
log_level(char *id)
{
char name[20] = { 0 };
size_t len = 0;
int cfgGlobal, cfgId;
if (id == NULL)
return LOG_LEVEL_ERROR;
len = strlen(id);
if (len == 0 || len > 15)
return LOG_LEVEL_ERROR;
strcpy(name, "log:");
strcat(name, id);
cfgGlobal = config_get_int("log", LOG_LEVEL_WARN);
cfgId = config_get_int(name, cfgGlobal);
if (cfgId > LOG_LEVEL_ERROR) {
cfgId = LOG_LEVEL_ERROR;
}
return cfgId;
}
static void
log_message_raw_v(enum LogLevel l, char *id, char *fmt, va_list argp)
{
if (l < log_level(id)) {
return;
}
if (logFile == 0) {
char *name = config_get_string("out", 0);
if (name) {
logFile = fopen(name, "a+t");
if (logFile == 0) {
perror(name);
}
}
if (logFile == 0) {
logFile = stdout;
}
}
vfprintf(logFile, fmt, argp);
}
void
log_message(enum LogLevel l, char *where, int line, char *id,
char *fmt, ...)
{
va_list argp;
if (l < log_level(id)) {
return;
}
#ifdef NON_DIFFABLE_OUTPUT
log_message_raw(l, id, "%s - %s:%d - %s: ", levelName[l],
nice_path(where), line, id);
#endif
log_message_raw(l, id, "%s - %s: ", levelName[l], id);
va_start(argp, fmt);
log_message_raw_v(l, id, fmt, argp);
va_end(argp);
log_message_raw(l, id, "\n");
if (l >= LOG_LEVEL_ERROR) {
fflush(logFile);
/*exit(1);*/
}
fflush(logFile);
}
void
log_message_raw(enum LogLevel l, char *id, char *fmt, ...)
{
va_list argp;
if (l < log_level(id)) {
return;
}
va_start(argp, fmt);
log_message_raw_v(l, id, fmt, argp);
va_end(argp);
}