Search code examples
c++logginglog4cplus

Different files for different levels


I am creating a parser and I want to output the Debug and the WARN messages to different files.

The code is very straightforward:

 logger(log4cplus::Logger::getInstance(LOG4CPLUS_TEXT("TParser")));
 LOG4CPLUS_WARN/DEBUG(logger, "XYZ");

I tried to use the following configuration file

log4cplus.logger.TParser=DEBUG, TD

log4cplus.appender.TD=log4cplus::RollingFileAppender
log4cplus.appender.TD.MaxFileSize=5MB
log4cplus.appender.TD.MaxBackupIndex=5
log4cplus.appender.TD.layout=log4cplus::TTCCLayout
log4cplus.appender.TD.File=debug.log

log4cplus.logger.TParser=WARN, TW
log4cplus.appender.TW=log4cplus::RollingFileAppender
log4cplus.appender.TW.MaxFileSize=5MB
log4cplus.appender.TW.MaxBackupIndex=5
log4cplus.appender.TW.layout=log4cplus::TTCCLayout
log4cplus.appender.TW.File=trace.log

But the Debug is not bei logger(log4cplus::Logger::getInstance(LOG4CPLUS_TEXT("TksParser")))ng generated... if I remove the [ log4cplus.logger.TParser=WARN, TW ] and the lines after that it generates the debug.

I also don't want to output the data to the console. I'm having some hard time triyng to learn how to use, but there is not a lot of content about log4cplus


Solution

  • One of problems of your properties file is that you have two lines setting value to log4cplus.logger.TParser. The line setting this property is overwritten by the second line setting this property.

    As for the separate files for separate log levels, well, it is possible but it is not something that you usually do. First, realise that there are many more log levels than just DEBUG and WARN like INFO, ERROR, FATAL, TRACE. Where would those go?

    You can log different log levels to different files by using filters. If you literally want to output only DEBUG log level (and not both DEBUG and TRACE log levels) into a file, use LogLevelMatchFilter (or LogLevelRangeFilter if you want a range of log levels) to set up an appender that will only log the DEBUG log level events. Then set up another appender with filter matching the WARN log level and attach it to the same logger. In your case, you would use this:

    log4cplus.logger.TParser=DEBUG, TD, TW
    

    To avoid the logs from one logger reaching the root logger, disable the additivity:

    log4cplus.additivity.TParser=false
    

    With this line, events that will reach the TParser logger will not propagate further towards the root logger.