hlswmaster-ng/logging.cpp
2006-02-02 16:55:44 +01:00

100 lines
1.5 KiB
C++

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdarg.h>
#include <errno.h>
#include <string.h>
#include "logging.h"
#define BUFLEN 1024
LogSystem::LogSystem() : output(0), priority(0)
{
buffer = new char[BUFLEN];
}
LogSystem::~LogSystem()
{
delete buffer;
if (output)
delete output;
}
LogSystem* LogSystem::getInstance()
{
static LogSystem ls;
return &ls;
}
void LogSystem::init(int prio, LogOutput* out)
{
LogSystem* ls = getInstance();
if (ls->output)
delete ls->output;
ls->output = out;
ls->priority = prio;
}
void LogSystem::log(int prio, const char* fmt, ...)
{
LogSystem* ls = getInstance();
if (prio > ls->priority || !ls->output)
return;
va_list az;
int len;
va_start(az, fmt);
len = vsnprintf(ls->buffer, BUFLEN, fmt, az);
va_end(az);
if (errno) {
strncpy(ls->buffer + len, ": ", BUFLEN - len);
len += 2;
strncpy(ls->buffer + len, strerror(errno), BUFLEN - len);
errno = 0;
}
ls->output->write(ls->buffer);
}
/* ------- */
void StdErrLog::write(const char* buf)
{
fprintf(stderr, "%s\n", buf);
}
/* ------- */
FileLog::FileLog(const char* filename)
{
if (!(logfile = fopen(filename, "a" )))
LogSystem::log(LOG_CRIT, "Can not open logfile '%s'", filename);
fprintf(logfile, "-----------------\n");
}
FileLog::~FileLog()
{
fclose(logfile);
}
void FileLog::write(const char* buf)
{
time_t tzgr;
char tbuf[64];
time(&tzgr);
strftime(tbuf, sizeof(tbuf), "%b %d %H:%M:%S :", localtime(&tzgr));
fprintf(logfile, "%s %s\n", tbuf, buf);
fflush(logfile);
}