Reputation: 1054
Let's consider example from boost::log doc.
void init()
{
logging::add_file_log
(
keywords::file_name = "sample_%N.log",
keywords::rotation_size = 10 * 1024 * 1024,
keywords::open_mode = (std::ios::out | std::ios::app),
keywords::format = "[%TimeStamp%]: %Message%"
);
logging::core::get()->set_filter
(
logging::trivial::severity >= logging::trivial::info
);
}
int main(int, char*[])
{
init();
logging::add_common_attributes();
using namespace logging::trivial;
src::severity_logger< severity_level > lg;
BOOST_LOG_SEV(lg, trace) << "A trace severity message";
return 0;
}
First time I start my application and file sample_0.log
is created. Second time I start my application new message is appended to same file sample_0.log
. I want sample_1.log
to be created by application. I want to rotate log files every time application runs. How can I archive this with boost::log
? Thanks.
Upvotes: 2
Views: 1501
Reputation: 10614
You probably want not to rotate the file on startup (which means to close the current file and open a new one) but rather to generate a file name that doesn't clash with the files that were left by the previous runs of your application.
Two things need to be done for this. First, you have to configure the file collector, which will receive rotated log files and optionally manage them. File collector operates on one target directory, where all the rotated files are stored. You can specify that directory by adding target
named parameter to your add_file_log
call; this will create a file collector for your sink. Note that the target directory can be the same as the one your sink creates the file in - it will simply mean that moving the rotated log file to the target directory is a no-op.
Second, on your application startup, the scan_for_files
method needs to be called on the sink backend. This will cause the file collector scan the target directory for log files that could have been left from the previous runs. If the file name pattern includes a file counter, the call can also detect the next counter value, which is what you want. The add_file_log
function will do this automatically for you, if you configured the file collector (i.e. added the target
named parameter), but if you create the sink manually, you will have to call it yourself.
Managing rotated files, including the scan_for_files
functionality, is documented here.
Upvotes: 3