log4cpp::RollingFileAppender – How to Backup and Roll Over log files?
It is very important to log the events in your software both for analytics and debugging. Log4cpp is helpful for logging in with C++. Log4Cpp::File Appender can be used to direct the output of logs to a file. But there are certain challenges that you may face while using log files
- The files can soon reach the maximum size your Operating System may support.
- The log file gets corrupted and you lose all of the valuable data.
To deal with these scenarios, that you split files as soon as they reach a specified size and backup the split files. One way is to write a script which will periodically do this. But you can use log4cpp for this purpose. Log4Cpp::RollingFileAppender can be used to specify the maximum size of the file size and the number of backup files you want to create
#include <stdio.h>
#include <stdlib.h>
#include <log4cpp/Category.hh>
#include <log4cpp/RollingFileAppender.hh>
#include <log4cpp/SimpleLayout.hh>
#define LOGFILE "/home/user/test.log"
int main()
{
/*Setting up Appender, layout and Category*/
log4cpp::Appender *appender = new log4cpp::RollingFileAppender("FileAppender",LOGFILE,100,12);
log4cpp::Layout *layout = new log4cpp::SimpleLayout();
log4cpp::Category& category = log4cpp::Category::getInstance("Category");
appender->setLayout(layout);
category.setAppender(appender);
category.setPriority(log4cpp::Priority::INFO);
category.info("This is for tracing the flow");
category.notice("This is to notify certain events");
category.warn("This is to generate certain warnings");
}
Each execution of the file will create new log files since the maximum size for the log files is 100 chars and the number of characters for the log is 129. So you can see the files test.log.1, test.log.2 and so on based on the number of times you executed the program.
The syntax for Log4Cpp::RollingFileAppender is as follows
RollingFileAppender(const std::string &name, const std::string &fileName, size_t maxFileSize=10 *1024 *1024, unsigned int maxBackupIndex=1, bool append=true, mode_t mode=00644)
Check the above values with the ones we have specified in the program. You can periodically backup (and then remove) the multiple log files save the man log file (here test.log)
Comments:
how to specify backup index in config file