该类主要实现按天来记录日志,同时日志文件超过规定大小时进行备份,多线程安全。
备份函数如下:
void Logger::Rollover(std::string& filename)
{
RolloverFiles(filename);
std::ostringstream source_oss;
std::ostringstream target_oss;
source_oss.str("");
target_oss.str("");
source_oss << filename;
target_oss << filename << "." << 1;
std::string const source (source_oss.str ());
std::string const target (target_oss.str ());
std::remove (target.c_str());
std::rename(source.c_str(), target.c_str());
}
void Logger::RolloverFiles(std::string& filename)
{
std::ostringstream buffer;
long ret ;
if(_curIndex == _maxBackupIndex)
{
buffer<<filename<<"."<<_curIndex;
ret = std::remove(buffer.str().c_str());
}
std::ostringstream source_oss;
std::ostringstream target_oss;
for (int i = _curIndex; i >= 1; --i)
{
source_oss.str("");
target_oss.str("");
source_oss << filename << "." << i;
target_oss << filename << "." << (i+1);
std::string const source (source_oss.str ());
std::string const target (target_oss.str ());
ret =std::remove (target.c_str());
std::rename(source.c_str(), target.c_str());
}
if(_curIndex!=(_maxBackupIndex-1))
_curIndex++;
}
写日志实现函数如下:
void Logger::writeLog(LOG_LEVEL level, std::string msg,std::string filename, int line)
{
CResGuard::CGuard gd(_logrs);
std::string fn= GetFileName(level);
time_t t;
time(&t);
struct tm tp;
localtime_s(&tp,&t);
char now_str[100]={0};
strftime(now_str, 100, "%Y-%m-%d %H:%M:%S", &tp);
errno_t rt = fopen_s(&_fo,fn.c_str(), "a");
if (rt != 0) {
if(_fo)
fclose(_fo);
return;
}
fprintf_s(_fo, "%s %s[%d] :%s\r\n",now_str,filename.c_str(),line, msg.c_str());
printf_s("%s %s[%d] :%s\r\n",now_str,filename.c_str(),line, msg.c_str());
fseek(_fo,0,SEEK_END);
long position = ftell(_fo);
fclose(_fo);
if(position>_maxFileSize)
{
Rollover(fn);
}
}
为了方便调用,定义了一个宏
#define HUALOG_MSG(level, msg ) SLogger::instance()->writeLog(level ,msg,__FILE__,__LINE__);
完整代码下载地址: