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.

This this post, I am showing the example code for configuring log4j using properties file

Steps to perform Hibernate Logging by Log4j using properties file

There are two ways to perform logging using log4j using properties file:

  1. Load the log4j jar files with hibernate
  2. Create the file inside the src folder (parallel with hibernate.cfg.xml file)

Example of Hibernate Logging by Log4j using properties file

You can enable logging in hibernate by following only two steps in any hibernate example. This is the first example of hibernate application with logging support using log4j.

1. Create a maven java project and update log4j dependencies


2. Create 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.layout.ConversionPattern=[%t] %-5p %c %x - %m%n

log4j.appender.fileAppender.layout.ConversionPattern=[%t] %-5p %c %x - %m%n

3. Configure and test the application

package com.javatportal;

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

		//Log in console in and log file
		logger.debug("Log4j appender configuration is successful !!");