Configuring Log4j programmatically

Let us see a very simple program to configure Log4j programmatically. Though Log4j environment is fully configurable programmatically. However, it is always recommended to configure log4j using configuration files like / log4j.xml file.

In the below example, We will create a simple class named 'Log4jConfigExample' and configure log4j programmatically.

Here BasicConfigurator.configure() is used to quickly configure the package and creates a simple log4j setup. And this method is hardwired to add to the root logger a ConsoleAppender and set the appender layout to a PatternLayout with the default pattern "%r [%t] %-5p %c - %m%n" . By default, the root logger is set to DEBUG level.

package com.log;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;

public class Log4jConfigExample {
	// Defining the static logger variable
	   static Logger logger = Logger.getLogger(Log4jConfigExample.class);
	   public void testMethod() {
		     logger.debug("Hello... In test method!");

	   public static void main(String[] args) {

	     // Set up a simple configuration that logs on the console.
	     BasicConfigurator.configure();"Logging started application.");
	     Log4jConfigExample example = new Log4jConfigExample();
	     example.testMethod();"Close application.");

After executing the above sample program, the output should look like below:

0 [main] INFO com.log.Log4jConfigExample  - Logging started application.
1 [main] DEBUG com.log.Log4jConfigExample  - Hello... In test method!
1 [main] INFO com.log.Log4jConfigExample  - Close application.

We can also parse configuration file and set up logging accordingly by using PropertyConfigurator class.

In the next tutorials we will see more in detail using configuration files for Log4j.

Log4j Tutorials: 

Add new comment