Porting Log.cpp to C++98

This commit is contained in:
Koncord 2016-08-17 05:52:40 +08:00
parent a92ef8b6bd
commit ee8d9895dc

View File

@ -6,11 +6,13 @@
#include <iostream> #include <iostream>
#include <cstring> #include <cstring>
#include <ctime> #include <ctime>
#include <cstdio>
#include <sstream>
#include "Log.hpp" #include "Log.hpp"
using namespace std; using namespace std;
Log *Log::sLog = nullptr; Log *Log::sLog = NULL;
Log::Log(int logLevel) : logLevel(logLevel) Log::Log(int logLevel) : logLevel(logLevel)
{ {
@ -19,17 +21,17 @@ Log::Log(int logLevel) : logLevel(logLevel)
void Log::Create(int logLevel) void Log::Create(int logLevel)
{ {
if(sLog != nullptr) if(sLog != NULL)
return; return;
sLog = new Log(logLevel); sLog = new Log(logLevel);
} }
void Log::Delete() void Log::Delete()
{ {
if(sLog == nullptr) if(sLog == NULL)
return return
delete sLog; delete sLog;
sLog = nullptr; sLog = NULL;
} }
const Log &Log::Get() const Log &Log::Get()
@ -51,32 +53,37 @@ const char* getTime()
void Log::print(int level, const char *file, int line, const char *message, ...) const void Log::print(int level, const char *file, int line, const char *message, ...) const
{ {
if(level < logLevel) return; if(level < logLevel) return;
std::string str = "[" + string(getTime()) + "] "; std::stringstream sstr;
sstr << "[" << getTime() << "] ";
if(file != 0 && line != 0) if(file != 0 && line != 0)
str += "["+ string(file) + ":" + to_string(line) + "] "; {
sstr << "[" << file << ":";
sstr << line << "] ";
}
str += "["; sstr << "[";
switch(level) switch(level)
{ {
case LOG_WARN: case LOG_WARN:
str += "WARN"; sstr << "WARN";
break; break;
case LOG_ERROR: case LOG_ERROR:
str += "ERR"; sstr << "ERR";
break; break;
case LOG_FATAL: case LOG_FATAL:
str += "FATAL"; sstr << "FATAL";
break; break;
default: default:
str += "INFO"; sstr << "INFO";
} }
str += "]: "; sstr << "]: ";
str += message; sstr << message;
if(str.back() != '\n') char back = *sstr.str().rbegin();
str += '\n'; if(back != '\n')
sstr << '\n';
va_list args; va_list args;
va_start(args, message); va_start(args, message);
vprintf(str.c_str(), args); vprintf(sstr.str().c_str(), args);
va_end(args); va_end(args);
} }