Configure Log4j using Properties File in Java

Log4j is a Logging Framework based on Java. We can Configure the Apache Log4j using Properties File with the help of PropertyConfigurator class. The PropertyConfigurator class Allows the Configuration of log4j from External File. The Class PropertyConfigurator containd static Method configure(String configFilename) which helps to load the File.

We can configure Log4j using Properties Configuration as well as XML Configuration. In this Tutorial We will see how to Configure Log4j using Properties File. To implement Apache Logger in Our Project We need log4j.jar So Download Apache Log4j Before Running this Demo.

Project Structure:-

log4j using properties file

Demo to Configure Log4j using Properties File in java:-

package com.javaartifacts;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class LoggerTest {

	public static Logger logger = Logger.getLogger(LoggerTest.class);
	
	public static void main(String[] args){
		
		PropertyConfigurator.configure("log4j.properties");
		
		logger.info("configure log4j using properties file in java");
	}
}

log4j.properties file

log4j.rootLogger=DEBUG, consoleAppend, fileAppend

log4j.appender.consoleAppend=org.apache.log4j.ConsoleAppender
log4j.appender.consoleAppend.Target=System.out
log4j.appender.consoleAppend.layout=org.apache.log4j.PatternLayout
log4j.appender.consoleAppend.layout.ConversionPattern=%t %-5p %c{2} - %m%n 

log4j.appender.fileAppend=org.apache.log4j.RollingFileAppender
log4j.appender.fileAppend.File=loggerdemo.log
log4j.appender.fileAppend.layout=org.apache.log4j.PatternLayout
log4j.appender.fileAppend.layout.conversionPattern=%d{MM-dd HH:mm:ss.S} %t %m%n

output:-

main INFO  javaartifacts.LoggerTest - configure log4j using properties file in java

Above Log4j.properties File is Configured to Log on the Console as well as to the File Named loggerdemo.log. Now if You want to create the log file on daily basis, then You can change the fileAppend Configuration with Below Configuration.

log4j.appender.fileAppend=org.apache.log4j.DailyRollingFileAppender
log4j.appender.fileAppend.File=loggerdemo.log
log4j.appender.fileAppend.layout=org.apache.log4j.PatternLayout
log4j.appender.fileAppend.layout.conversionPattern=%d{MM-dd HH:mm:ss.S} %t %m%n
log4j.appender.P.DatePattern='.'yyy-MM-dd

Leave a Reply

Your email address will not be published. Required fields are marked *