Log4j – Configure Appenders Programmatically

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.

Log4j allows logging requests to print to multiple destinations. In log4j speak, an output destination is called an appender. They vary from console, files, GUI components, remote socket servers to JMS.

In previous post, we learned about configuring log4j dependency in your application using maven. In this post, I am forwarding the discussion by showing programmatic way to configure appenders in log4j.

Step 1) Create maven project and update dependencies

These steps, we have already seen in my last post. Please follow first 3 steps from previous post about basic log4j configuration, if you have not gone through it.

Step 2) Add ConsoleAppender and RollingFileAppender in root logger

I have written a sample code to demonstrate that how a console and file appender can be added programmatically. I will suggest to play with the code and add various options to appenders to see their effect. Its a great way of learning the things.

package com.howtodoinjava;

import java.io.IOException;

import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.RollingFileAppender;

public class ProgrammticallyConfigureAppenderExample {

private static final Logger log = Logger.getLogger(ProgrammticallyConfigureAppenderExample.class);

public static void main(String[] args)
//This is the root logger provided by log4j
Logger rootLogger = Logger.getRootLogger();

//Define log pattern layout
PatternLayout layout = new PatternLayout("%d{ISO8601} [%t] %-5p %c %x - %m%n");

//Add console appender to root logger
rootLogger.addAppender(new ConsoleAppender(layout));
//Define file appender with layout and output log file name
RollingFileAppender fileAppender = new RollingFileAppender(layout, "demoApplication.log");

//Add the appender to root logger
catch (IOException e)
System.out.println("Failed to add appender !!");
//Let verify the log messages
log.info("Welcome to www.HowToDoInJava.com");
log.debug("Welcome to www.HowToDoInJava.com");
log.error("Welcome to www.HowToDoInJava.com");
log.fatal("Welcome to www.HowToDoInJava.com");

Step 3) Test the application

Run above program as java application from your IDE and observe the output. Log messages are appreaed in console as:

2013-04-08 14:22:27,567 [main] INFO  com.howtodoinjava.ProgrammticallyConfigureAppenderExample  -
Welcome to www.HowToDoInJava.com
2013-04-08 14:22:27,567 [main] DEBUG com.howtodoinjava.ProgrammticallyConfigureAppenderExample  -
Welcome to www.HowToDoInJava.com
2013-04-08 14:22:27,567 [main] ERROR com.howtodoinjava.ProgrammticallyConfigureAppenderExample  -
Welcome to www.HowToDoInJava.com
2013-04-08 14:22:27,567 [main] FATAL com.howtodoinjava.ProgrammticallyConfigureAppenderExample  -
Welcome to www.HowToDoInJava.com

And same log messages are going to log file created in root of your project i.e. demoApplication.log file.

Let me know if something is not clear or i am missing anything.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

8 thoughts on “Log4j – Configure Appenders Programmatically”

  1. Dear Lokesh,

    I have created one stand alone application, I need logs to be generated inside installer file but currently logs are generated where I have given the path hardcoded. Please help me

  2. log4j.properties

    >log4j.appender.stdout.layout.ConversionPattern=[%5p] %d [%c{1}] (%F:%M:%L)%n%m%n%n
    >log4j.appender.R.layout.ConversionPattern=[%5p] %d [%c{1}] (%F:%M:%L)%n%m%n%n

    java file

    import java.util.Enumeration;
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.apache.log4j.Appender;
    import org.apache.log4j.FileAppender;
    import org.apache.log4j.Logger;
    import org.apache.log4j.RollingFileAppender;
    public class Log4jFile {
    	private static final Log LOG = LogFactory.getLog(Log4jFile.class);
    	 * To maintain log files unique for different clients
    	 * @param fileName
    	public void log4j(String fileName){
    		String logFileName = fileName+".log";
    		LOG.info("\n**************Log file for this run: " + logFileName + "\n**************\n");
    		Logger rootLogger = Logger.getRootLogger();
    		Enumeration appenders = rootLogger.getAllAppenders();
    		FileAppender fa = null;
    			Appender currAppender = (Appender) appenders.nextElement();
    			if(currAppender instanceof FileAppender){
    				fa = (RollingFileAppender) currAppender;
    		if(fa != null){
    			//To test in local
    			//To test in production
    			LOG.info("No File Appender found");
  3. Can you give pointers to how SocketAppender can be configured programmatically? I have looked around everywhere and could not find any advice on using SocketAppenders without the log4j-server.properties file.

  4. How to resolve the error “The method addAppender(ConsoleAppender) is undefined for the type Logger” in line 26 : rootLogger.addAppender(new ConsoleAppender(layout)); Thanks in advance.


Leave a Comment


A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.