/* logger.c
*
* Copyright 2025 Francois Techene
*
* This program 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 3 of the License, or
* (at your option) any later version.
*
* This program 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 this program. If not, see .
*
* SPDX-License-Identifier: GPL-3.0-or-later
*/
#include
#include
#include
#include "logger.h"
Logger logger;
void
init_logger(LogLevel level,
LogOutputMethod out,
char* file_path)
{
logger.debug = log_debug;
logger.info = log_info;
logger.warn = log_warn;
logger.error = log_error;
logger.log_level = level;
logger.output_method = out;
logger.file_path = file_path;
if (out == CONSOLE_OUT) {
logger.log = log_to_console;
}
else if (out == FILE_OUT) {
FILE* file;
logger.log = log_to_file;
// Empty log file. If the file cannot be created, the log output
// is set to NONE_OUT;
//
file = fopen(logger.file_path, "w");
if(!file) {
logger.output_method = NONE_OUT;
logger.log = log_to_none;
return;
}
fprintf(file, "");
fclose(file);
}
else {
logger.log = log_to_none;
}
}
void
log_to_none(char* format, ...)
{
return;
}
void
log_to_console(char* format, ...)
{
va_list ap;
va_start(ap, format);
vprintf(format, ap);
va_end(ap);
printf("\n");
}
void
log_to_file(char* format, ...)
{
FILE* file;
va_list ap;
// Open file in Append Binary mode so the
// new line character is not converted.
//
file = fopen(logger.file_path, "ab");
if(!file) {
return;
}
va_start(ap, format);
vfprintf(file, format, ap);
va_end(ap);
// Using Unix New Line character for tail to
// read correctly on Linux.
//
fprintf(file, " \x0A\r");
fclose(file);
}
void
log_debug(char* format, ...)
{
va_list ap;
char log[256] = "";
if (logger.log_level < DEBUG_LEVEL) {
return;
}
va_start(ap, format);
vsprintf(log, format, ap);
va_end(ap);
logger.log("DEBUG: %s", log);
}
void
log_info(char* format, ...)
{
va_list ap;
char log[256] = "";
if (logger.log_level < INFO_LEVEL) {
return;
}
va_start(ap, format);
vsprintf(log, format, ap);
va_end(ap);
logger.log("INFO: %s", log);
}
void
log_warn(char* format, ...)
{
va_list ap;
char log[256] = "";
if (logger.log_level < WARNING_LEVEL) {
return;
}
va_start(ap, format);
vsprintf(log, format, ap);
va_end(ap);
logger.log("WARNING: %s", log);
}
void
log_error(char* format, ...)
{
va_list ap;
char log[256] = "";
if (logger.log_level < ERROR_LEVEL) {
return;
}
va_start(ap, format);
vsprintf(log, format, ap);
va_end(ap);
logger.log("ERROR: %s", log);
}