abumq / easyloggingpp

C++ logging library. It is extremely powerful, extendable, light-weight, fast performing, thread and type safe and consists of many built-in features. It provides ability to write logs in your own customized format. It also provide support for logging your classes, third-party libraries, STL and third-party containers etc.
MIT License
3.75k stars 918 forks source link

How do I close the log, delete the log, and then start logging again while the program is running #809

Open hgc1 opened 2 years ago

jidn commented 2 years ago

I wrote this a couple of years ago to move the log from WinPE without a formatted drive, to a formatted drive before reboot so post reboot the logging could continue. I dug around in the code just enought to accomplish the task. Once it did what I wanted, I moved on, so I'm not sure if this is the "proper" way to do it or not.

While I move the log and continue logging, your use case would be simpler. Instead of copying the file, just std::filesystem::remove(). Hope this helps.

// Get current configuration and log file name
auto logger = el::Loggers::getLogger("default");
auto config = logger->configurations();
std::filesystem::path current_log_file = logger->typedConfigurations()->filename(el::Level::Info);

// Shut down the logging file.
logger->typedConfigurations()->acquireLock();
el::base::type::EnumType starting_level = el::LevelHelper::kMinValid;
el::LevelHelper::forEachLevel(&starting_level, [&](void) -> bool {
     logger->typedConfigurations()->fileStream(el::LevelHelper::castFromInt(starting_level))->close();
     return false;
});

// Copy log file from current_log_file to new_logfile_path

// Restart logging from the new location
config->setGlobally(el::ConfigurationType::Filename, new_logfile_path.string().c_str());
logger->configure(*config);