#include "Logger.h"
#include <fstream>
#include <sstream>
#include <time.h>
Logger* Logger::pInstance = 0;
string GetSystemTime()
{
time_t timep;time (&timep);
char tmp[64];
strftime(tmp, sizeof(tmp), "%Y-%m-%d %H:%M:%S",localtime(&timep));
string s(tmp);
return s;
}
Logger::Logger(void)
{
// 默认在log目录下
LoggerInit("./log",true,true,true,NOT_OUT);
#ifdef WIN32
InitializeCriticalSection(&gSection);
#elif linux
pthread_mutex_init(&mtx,NULL);
#endif
}
void Logger::LockCriticalSection()
{
#ifdef WIN32
EnterCriticalSection(&gSection);
#elif linux
pthread_mutex_lock(&mtx);
#endif
}
void Logger::UnlockCriticalSection()
{
#ifdef WIN32
LeaveCriticalSection(&gSection);
#elif linux
pthread_mutex_unlock(&mtx);
#endif
}
Logger::~Logger(void)
{
#ifdef WIN32
DeleteCriticalSection(&gSection);
#elif linux
pthread_mutex_destroy(&mtx);
#endif
if(Logger::pInstance)
{
delete Logger::pInstance;
Logger::pInstance = 0;
}
}
Logger* Logger::GetInstance()
{
if(pInstance == 0)
pInstance = new Logger;
return pInstance;
}
void Logger::LoggerInit(string str, bool normal, bool warn,bool error,int level)
{
strFilePath = str;
bNormal = normal;
bError = error;
bWarn = warn;
this->level = level;
MakeLogDir(str);
}
void Logger::AppendLog(enum LOGGER_TYPE type,string filedir, string funcname, int line, string log)
{
string strTemp = strFilePath;
switch(type)
{
case NORMAL:
if(!bNormal)
return;
strTemp += "/normal";
break;
case WARN:
if(!bWarn)
return;
strTemp += "/warn";
break;
case ERR:
if(!bError)
return;
strTemp += "/error";
break;
}
//构造输出
string strContext;
stringstream out;
out<<"{\"time\":\""<<GetSystemTime()<<"\",\"source\":\""<<filedir<<"\",\"func\":\""<<funcname<<"\",\"line\":\""<<line<<"\",\"msg\":\""<<log<<"\"}";
strContext = out.str();
if(level<=type)
cout<<strContext<<endl;
LockCriticalSection();//操作日志文件
ofstream ofresult(strTemp.c_str(),ios::app);
ofresult<<strContext<<endl;
ofresult.flush();
ofresult.close();
UnlockCriticalSection();//释放资源
}
// create log dir
void Logger::MakeLogDir(string strPath)
{
#ifdef WIN32
struct _stat stat;
if((_stat(strPath.c_str(),&stat) == 0) && (stat.st_mode & _S_IFDIR))
return;
else
{// make dir
_mkdir(strPath.c_str());
}
#elif linux
struct stat st;
if((stat(strPath.c_str(),&st) == 0) && S_ISDIR(st.st_mode))
return;
else
{// make dir
mkdir(strPath.c_str(),S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH);
}
#endif
}