diff --git a/include/Common/SimpleLog.h b/include/Common/SimpleLog.h index 0178f1c..401b888 100644 --- a/include/Common/SimpleLog.h +++ b/include/Common/SimpleLog.h @@ -36,7 +36,7 @@ class SimpleLog // Optionnaly, an automatic log rotation can be defined. Older files are renamed, appending .1, .2, .3, etc. // \param logFilePath Path to log file. If NULL, using stdout/stderr. If /dev/null, messages are completely dropped. // \param rotateMaxBytes Maximum file size, after which a new file is created. If zero, no limit. - // \param rotateMaxFiles Maximum number of files to keep (including the "current" file). If zero, no limit. + // \param rotateMaxFiles Maximum number of files to keep (including the "current" file). If zero, no limit. If one, a single file is created and cleared immediately, and messages are discarded after reaching rotateMaxBytes. // \param rotateNow If non-zero, the file is immediately rotated (independently of its size), otherwise it is appended. int setLogFile(const char* logFilePath = NULL, unsigned long rotateMaxBytes = 0, unsigned int rotateMaxFiles = 0, unsigned int rotateNow = 0); diff --git a/src/SimpleLog.cxx b/src/SimpleLog.cxx index 1ed1507..95c8111 100644 --- a/src/SimpleLog.cxx +++ b/src/SimpleLog.cxx @@ -144,6 +144,11 @@ int SimpleLog::Impl::logV(SimpleLog::Impl::Severity s, const char* message, va_l if (fp != NULL) { if ((ix + logFileSize > rotateMaxBytes) && (rotateMaxBytes > 0)) { closeLogFile(); + if (rotateMaxFiles == 1) { + // stop after first file + disableOutput = 1; + return -1; + } rotate(); if (openLogFile()) return -1; @@ -195,6 +200,9 @@ int SimpleLog::setLogFile(const char* logFilePath, unsigned long rotateMaxBytes, pImpl->disableOutput = 1; return 0; } + if (rotateMaxFiles < 0) { + rotateMaxFiles = 1; + } pImpl->rotateMaxBytes = rotateMaxBytes; pImpl->rotateMaxFiles = rotateMaxFiles; if (rotateNow) { @@ -269,6 +277,10 @@ int SimpleLog::Impl::openLogFile() if (logFilePath.length() == 0) { return 0; } + const char* mode = "a"; + if (rotateMaxFiles == 1) { + mode = "w"; + } fp = fopen(logFilePath.c_str(), "a"); if (fp == NULL) { return -1; @@ -371,7 +383,7 @@ void SimpleLog::Impl::rotate() } else { inFile = dirName + fileName + "." + std::to_string(oldIndex); } - if ((newIndex > rotateMaxFiles) && (rotateMaxFiles != 0)) { + if ((newIndex >= rotateMaxFiles) && (rotateMaxFiles != 0)) { // this file should be removed unlink(inFile.c_str()); } else {