#include <stdarg.h>
|
#include <stdio.h>
|
#include <time.h>
|
#include <syslog.h>
|
#include <sys/time.h>
|
|
#include "dgrid_logger.h"
|
|
namespace DGrid {
|
|
const char* COL_GR0 = "\E[30;60m";
|
const char* COL_RED = "\E[31;60m";
|
const char* COL_GRN = "\E[32;60m";
|
const char* COL_YEL = "\E[33;60m";
|
const char* COL_BLU = "\E[34;60m";
|
const char* COL_VIOL = "\E[35;60m";
|
const char* COL_CYAN = "\E[36;60m";
|
const char* COL_GR1 = "\E[37;60m";
|
const char* COL_NO__ = "\E[38;60m";
|
const char* COL_WHITE = "\E[39;60m";
|
const char* COL_NORM = "\E[0m";
|
|
static bool useSysLog = false;
|
static bool forceLogFlush = false;
|
static int logLevel = LOG_INFO;
|
static bool logTime = true;
|
static FILE* logFile = NULL;
|
static std::string log_name;
|
|
void __attribute__ (( constructor)) dgrid_logger_init(void)
|
{
|
}
|
|
void __attribute__ (( destructor)) dgrid_logger_fini(void)
|
{
|
if (logFile && logFile != stdout && logFile != stderr) {
|
fclose(logFile);
|
logFile = NULL;
|
}
|
}
|
|
void setLogLevel(int severity)
|
{
|
logLevel = severity;
|
}
|
|
void setForcedLogFlush(bool f)
|
{
|
forceLogFlush = f;
|
}
|
|
const char* getSeverityColor(int severity)
|
{
|
switch(severity) {
|
case LOG_EMERG:
|
case LOG_ALERT:
|
case LOG_CRIT:
|
case LOG_ERR:
|
return COL_RED;
|
case LOG_WARNING:
|
return COL_YEL;
|
case LOG_NOTICE:
|
return COL_GRN;
|
case LOG_INFO:
|
return COL_NORM;
|
case LOG_DEBUG:
|
return COL_CYAN;
|
}
|
return COL_NORM;
|
}
|
|
void writeLog(int severity, const char* format, ...)
|
{
|
if(severity > logLevel)
|
return;
|
|
va_list ap;
|
va_start(ap, format);
|
if (useSysLog && !logFile) {
|
vsyslog(severity, format, ap);
|
} else {
|
if (logTime) {
|
time_t t = time(NULL);
|
tm ttm = *localtime(&t);
|
if (logFile)
|
fprintf(logFile, "[%02d:%02d:%02d] ", ttm.tm_hour, ttm.tm_min, ttm.tm_sec);
|
else
|
printf("[%02d:%02d:%02d] ", ttm.tm_hour, ttm.tm_min, ttm.tm_sec);
|
}
|
if (logFile) {
|
fprintf(logFile, getSeverityColor(severity));
|
vfprintf(logFile, format, ap);
|
fprintf(logFile, "%s\n", COL_NORM);
|
if(forceLogFlush)
|
fflush(logFile);
|
} else {
|
printf(getSeverityColor(severity));
|
vprintf(format, ap);
|
printf("%s\n", COL_NORM);
|
}
|
}
|
va_end(ap);
|
}
|
|
bool setLogFile(const std::string fname)
|
{
|
log_name = fname;
|
if (logFile) {
|
fclose(logFile);
|
logFile = NULL;
|
}
|
if (log_name.empty())
|
return true;
|
|
if("stdout" == log_name) {
|
logFile = stdout;
|
} else if("stderr" == log_name) {
|
logFile = stderr;
|
} else {
|
logFile = fopen(log_name.c_str(), "a");
|
}
|
return !!logFile;
|
}
|
|
void setSysLog(std::string ident)
|
{
|
useSysLog = true;
|
openlog(ident.c_str(), LOG_PID, LOG_DAEMON);
|
}
|
|
void restartLogger()
|
{
|
setLogFile(log_name);
|
};
|
|
} // namespace DGrid
|