log4cpp日志无法分卷的解决方案

来源:互联网 发布:软件开发收入确认 编辑:程序博客网 时间:2024/04/28 17:09


我们的项目采用log4cpp作为日志输出模块,但在使用中发现,如果是一个Services,或者是在Windows Server版本上,会出现日志无法正常分割的现象。即日志一直往一个文件里持续写,即使超过规定的文件大小,也不会分卷。

log4cpp中分割日志的核心算法为:(假设允许的最大文件个数为4)
1.关闭xxx.log.
2.删除 xxx.log.4
3.是一个loop, 将xxx.log.3--->xxx.log.4,xxx.log.2--->xxx.log.3,xxx.log.1----->xxx.log.2
4.将xxx.log--->xxx.log.1
5.打开xxx.log.

相关代码为:  

void RollingFileAppender::rollOver() {        ::close(_fd); // 1        if (_maxBackupIndex > 0) {             std::ostringstream oldName;             oldName << _fileName << "." << _maxBackupIndex << std::ends;             ::remove(oldName.str().c_str());   //2               size_t n = _fileName.length() + 1;             for(unsigned int i = _maxBackupIndex; i > 1; i--) {  //3                   std::string newName = oldName.str();                   oldName.seekp(n);                   oldName << i-1 << std::ends;                   ::rename(oldName.str().c_str(), newName.c_str());               }               ::rename(_fileName.c_str(), oldName.str().c_str()); //4        }        _fd = ::open(_fileName.c_str(), _flags, _mode);//5  }  

日志文件无法分割(目前发现只在win server版本无法work),原因出在步骤1,4,5上,
关闭文件后,随后将文件重命名,会导致重命名失败。通过打印错误码得知,错误码为32,意思为:文件句柄被占用。
解决方案为,往两个不同的文件里中写日志,不再只往一个文件名里写日志,交替写日志,交替关闭文件。write(A),close(B)---->Write(B),Close(A),----->Write(A),Close(B).
修改后的代码为:

void RollingFileAppender::rollOver() {          ::close(_fd);          if (_maxBackupIndex > 0) {              std::ostringstream oldName;              oldName << _fileName << "." << _maxBackupIndex << std::ends;              ::remove(oldName.str().c_str());              size_t n = _fileName.length() + 1;              for(unsigned int i = _maxBackupIndex; i > 1; i--) {                  std::string newName = oldName.str();                  oldName.seekp(n);                    oldName << i-1 << std::ends;                  ::rename(oldName.str().c_str(), newName.c_str());              }  if(_bUsingTempFile)              ::rename(_fileNameTmp.c_str(), oldName.str().c_str());  else              ::rename(_fileName.c_str(), oldName.str().c_str());          }  if(_bUsingTempFile)          _fd = ::open(_fileName.c_str(), _flags, _mode);  else          _fd = ::open(_fileNameTmp.c_str(), _flags, _mode);          _bUsingTempFile = !_bUsingTempFile;      }  
0 0
原创粉丝点击