in Coding, Java, Tutorial

Log4j Tutorial : How to send log messages to different log files?

One of the common requirement in Java projects, that are using Log4j logging, is to have different log files for each module (or layer) in the project. For example, if you have a web application, you may want to log the debug/info messages from the service layer to a service.log file and the log messages from the presentation layer to the web-app.log file and so on. This is very simple to achieve in Log4j.

Log4j has a concept called Category using which you can classify a package as a category and assign a appender to that category alone. To make this point clear, consider that we have the below Java classes in our project:

Now, if we want to send the log messages from to service.log and to dao.log files respectively, then the log4j configuration would be something like this: = INFO, serviceFileAppender = INFO, daoFileAppender
log4j.rootLogger = INFO, defaultAppender

As you can see in above snippet, we are defining two categories for the service and dao packages and associating them with the appenders serviceFileAppender and daoFileAppender respectively. These two appender are just any file appenders configured somewhere in the same file. So, all the log messages that coming from the classes which resides under the com.someapp.service package will go to the serviceFileAppender, which in turn will go to service.log. The same logic applies to dao.log also.

Apart from these two logs, we also defined the defaultAppender as the root logger. Means, the log messages from all the packages will go to defaultAppender, including the service and dao log messages. Yes! with the above configuration, the service and dao log messages will be there in two places. In their respective log appenders the defaultAppender.