How to log to multiple log files with log4j

Mar 6, 2011   JC    Comments

Back to Java coding!

We have a Java application that calls an external application and since it gets called quite often we figured we should probably log its standard output and standard error streams to a separate log file so we could easily locate issues with it later. This would also allow us to create a different message format for it and different handlers.

Luckily, it turned out that this is pretty easy to do with log4j, simply edit your file and add acategory (which is basically another logger).

For example:

# Add a new category/logger called "ExternalAppLogger" and specify
# the log level ("INFO") and the appender name ("extAppLogFile").
log4j.category.ExternalAppLogger=INFO, extAppLogFile

# Set the appender settings
log4j.appender.extAppLogFile.layout.ConversionPattern=%d %5p %C{1}: %n%m%n

Now in your Java code, you can create a separate Logger object for the above:

Logger extAppLogger = Logger.getLogger("ExternalAppLogger")"This message will be written to D:/MyCoolApp/logs/external-app.log.")