Using Log4j to selectively log to multiple files

You need to set up more categories in the log4j.properties file, this
can be done like so:

# The default root appender
log4j.rootLogger=A1

# A1 is set to be a ConsoleAppender which outputs to System.out.
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-22d{dd/MMM/yyyy HH:mm:ss}
%-8p %c [%t] – %m (%l)%n

# An extra category to a log file
log4j.category.AppLogging=A3

# A3 is set to be a FileAppender which will log all actions in the application.
log4j.appender.A3=org.apache.log4j.FileAppender
log4j.appender.A3.layout=org.apache.log4j.PatternLayout
log4j.appender.A3.layout.ConversionPattern=%-22d{dd/MMM/yyyy HH:mm:ss} – %m%n
log4j.appender.A3.file=application.log

Now in your code if you want a Logger for the root appender you use:

Logger logger = Logger.getLogger(MyClass.class.getName());

And if you want to log to the alternate category:

Logger appLogger = Logger.getLogger(“AppLogging”);

 

Checkout the below link for more details:

http://www.jguru.com/faq/view.jsp?EID=1311014

Advertisements
This entry was posted in Log4j and tagged , . Bookmark the permalink.

2 Responses to Using Log4j to selectively log to multiple files

  1. SonyaSunny says:

    Super post, Need to mark it on Digg
    Have a nice day
    SonyaSunny

  2. JC says:

    Thanks, it works!

    One thing I would though is the log level may be needed when you define the category.

    Example:
    log4j.rootLogger=INFO,A1

    In my case I had to specify the log level before it actually logged the message.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s