Files
plains/src/core/Logger.cpp
T

142 lines
3.3 KiB
C++

#include "Logger.hpp"
#include <iostream>
#include <ctime>
namespace Plains {
namespace Core {
using std::cout;
using std::cerr;
using std::endl;
Logger::Logger(enum Level logLevel) :
logLevel(logLevel),
debug(DEBUG, *this),
info(INFO, *this),
warn(WARN, *this),
fatal(FATAL, *this)
{
output = new ofstream("plains.log", std::ios_base::app);
if (!(*output)) {
cout << "Unable to open Logfile! writing to /tmp/plains.log" << endl;
output = new ofstream("/tmp/plains.log");
}
else {
debug << "Logfile successfully opened!" << commit;
}
}
Logger::~Logger() {
output->close();
delete output;
}
string Logger::genTimeStamp() {
time_t rawtime;
struct tm * timeinfo;
char buffer[80];
time (&rawtime);
timeinfo = localtime(&rawtime);
strftime(buffer,sizeof(buffer),"%b %d %H:%M:%S",timeinfo);
return string(buffer);
}
void Logger::setLogLevel(Level level) {
}
void Logger::log(Level lvl, const string& msg) { log ( lvl, msg.c_str() ); }
void Logger::log(Level lvl, const char* msg) {
switch ( lvl ) {
case DEBUG: debug.ln (msg); break;
case INFO: info.ln (msg); break;
case WARN: warn.ln (msg); break;
case FATAL: fatal.ln (msg); break;
}
}
Logger::Sink::Sink (const Level level, Logger& parent) :
level_(level),
parent_(parent),
lineIsPrefixed_(false) {}
void Logger::Sink::ln ( const string& msg ) {
ln(msg.c_str());
}
void Logger::Sink::ln ( const char* msg ) {
if ( level_ >= parent_.logLevel ) {
// If line has already been started, abort it and start new one:
if(lineIsPrefixed_) *parent_.output << endl;
prefixLine(true);
*parent_.output << msg << endl;
}
}
void Logger::Sink::prefixLine(bool resetToFalse) {
if (!lineIsPrefixed_) {
const char* lvlString;
switch ( level_ )
{
case DEBUG: lvlString = "DEBUG"; break;
case INFO: lvlString = "INFO"; break;
case WARN: lvlString = "WARN"; break;
case FATAL: lvlString = "FATAL"; break;
}
*parent_.output << Logger::genTimeStamp() << " [" << lvlString << "] ";
lineIsPrefixed_ = resetToFalse ? false : true;
}
}
Logger::Sink& Logger::Sink::operator<<(const string& msg) {
if ( level_ >= parent_.logLevel ) {
prefixLine();
*parent_.output << msg;
}
return *this;
}
Logger::Sink& Logger::Sink::operator<<(const char* msg) {
if ( level_ >= parent_.logLevel ) {
prefixLine();
*parent_.output << msg;
}
return *this;
}
Logger::Sink& Logger::Sink::operator<<(const long msg) {
if ( level_ >= parent_.logLevel ) {
prefixLine();
*parent_.output << msg;
}
return *this;
}
Logger::Sink& Logger::Sink::operator<<(const unsigned long msg) {
if ( level_ >= parent_.logLevel ) {
prefixLine();
*parent_.output << msg;
}
return *this;
}
Logger::Sink& Logger::Sink::operator<<(const char character) {
if ( level_ >= parent_.logLevel ) {
switch(character) {
// COMMIT - End message line
case 0:
*parent_.output << endl;
lineIsPrefixed_ = false;
break;
}
}
return *this;
}
}}