Configuring for 2(or more) different log4j files

I'm not really fond of configuring log4j. I know the basic stuff but then, didn't anticipate to be assigned a task to log into two different loggers. I usually just log in the console and leave the complexities to the guys who setup the application server in production.

My typical, simple log4j.properties

log4j.rootCategory=debug, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{dd/MM/yyyy HH:mm:ss} %c %m%n

What the above does is just simply to log in the console whenever it encounters a "debug" statement. Now, what I needed was to log to a different log. I didn't want to share with the console and I want specific things to be written to my other log file.

First off, make sure the log4j.properties is visible in your classpath.

Add the following code in your log4j.properties

log4j.logger.devpinoyLogger=DEBUG, dest1

log4j.appender.dest1=org.apache.log4j.RollingFileAppender
log4j.appender.dest1.maxFileSize=5000KB
log4j.appender.dest1.maxBackupIndex=3
log4j.appender.dest1.layout=org.apache.log4j.PatternLayout
log4j.appender.dest1.layout.ConversionPattern=%d{dd/MM/yyyy HH:mm:ss} %c %m%n
log4j.appender.dest1.File=${application.log.root}/MyOtherLogFile.log

The above listing  gives us a logger named devpinoyLogger. You might be wondering what dest1 is. It's an Appender, named dest1. Yes, you can name it anything you like. One last thing you might be wondering is ${application.log.root}. This is called a System Variable, it's a little different from an environment variable because this is something you either set in your application server or with the -D argument when you invoke a console application.

 

Now, going to the Java code.

 

Typically, you would call a logger like this.

Logger logger = Logger.getLogger(SomeClass.class);

To setup a different logger, just supply the logger name(in our case, devpinoyLogger) as the argument to getLogger.

Logger logger = Logger.getLogger("devpinoyLogger);

 

You can now log separately. I use this to log in two different files.

Logger logger1 = Logger.getLogger(SomeClass.class);

Logger logger2 = Logger.getLogger("devpinoyLogger");

public void testLog(){

    logger1.debug("This is logger 1 logging");

    logger2.debug("This is logger 2 logging");

}

Now, I know I didn't went into details. I expect you to have enough common sense to modify the above properties and code to fit your needs.

HTH. ;)

 

 

 

 

Published 01-26-2009 3:49 AM by lamia
Filed under: