Tuesday 29 July 2014

How to configure log4j using properties file

Log4j is a simple and flexible logging framework. Logging equips the developer with detailed context for application failures. With log4j it is possible to enable logging at runtime without modifying the application binary. The log4j package is designed so that these statements can remain in shipped code without incurring a heavy performance cost.
Two most common configuration options are in practice industry wide i.e. using xml configuration and using properties configuration.
In this post, I am showing the example code for configuring log4j using properties file.
Step 1) Create a maven java project and update log4j dependencies
Follow the steps given in this post related to configuring log4j with maven.
Step 2) Create log4j.properties file
This is the main properties file having all runtime configuration used by log4j. This file will have appenders information, log level information and output file names for file appenders.
log4j.rootLogger=DEBUG, consoleAppender, fileAppender

log4j.appender.consoleAppender=org.apache.log4j.ConsoleAppender
log4j.appender.consoleAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.consoleAppender.layout.ConversionPattern=[%t] %-5p %c %x - %m%n

log4j.appender.fileAppender=org.apache.log4j.RollingFileAppender
log4j.appender.fileAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.fileAppender.layout.ConversionPattern=[%t] %-5p %c %x - %m%n
log4j.appender.fileAppender.File=demoApplication.log
Step 3) Configure log4j.properties and test the application
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package default;
 
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
 
public class Log4jPropertiesConfigurationExample
{
    static Logger logger = Logger.getLogger(Log4jPropertiesConfigurationExample.class);
    public static void main(String[] args)
    {
        //PropertiesConfigurator is used to configure logger from properties file
        PropertyConfigurator.configure("log4j.properties");
 
        //Log in console in and log file
        logger.debug("Log4j appender configuration is successful !!");
    }
}
Output in console and demoApplication.log in project root folder:
[main] DEBUG com.howtodoinjava.Log4jPropertiesConfigurationExample  - Log4j appender configuration is successful !!

No comments:

Post a Comment