1

I have a class in which i am using log4j to log messages. I have log messages in if and else part of the code. I need to log the messages in if{} condition to a separate log file and the else part log messages to a separate log file. For example in the below code the message inside if should be logged in log1 file and inside else message should be logged in log2 file. I am using log4J XML configuration file. May i know if this is possible using log4j?? Any help is highly appreciated. Thanks in advance.

if(id=1){
logger.info("inside if");
}else{
logger.info("inside else");
}
user903676
  • 319
  • 1
  • 4
  • 10

2 Answers2

0

Just use/configure two FileAppenders with different file paths for your logger-path. Every logger can have more than one appender. This SO-answer contains an example how to do this (look there for multiple use of appender-ref-tag).

Community
  • 1
  • 1
Meno Hochschild
  • 42,708
  • 7
  • 104
  • 126
0

Could you use two loggers? Something like this:

Logger loggerIf = Logger.getLogger("com.foo.MyClass.if");
Logger loggerElse = Logger.getLogger("com.foo.MyClass.else");
if (id == 1) {
    loggerIf.info("inside if");
} else {
    loggerElse.info("inside else");
}

Then configure each logger to have a different appender, each pointing at a different file.

stripybadger
  • 4,539
  • 3
  • 19
  • 26
  • I doubt if system admins responsible for logging configuration will be happy if they find logger names not following package names but internal code details. – Meno Hochschild Apr 03 '14 at 15:29