Signup/Sign In
LAST UPDATED: APRIL 28, 2023

Log4j2 Programmatic Configuration in Java Class

Technology #java

    In this tutorial, we will learn how we can set up Log4j2 Programmatic Configuration in Java Class. If you want to configure Log4j2 programmatically in your Java code, you are at the right place.

    Generally, Log4j2 is set up using XML configuration, YAML configuration, Properties file, or in JSON file.

    We have covered all of these in different tutorials here:

    Log4j2 with XML Configuration File Example

    Log4j2 setup with Configuration in JSON File

    Log4j2 Configuration with Properties File

    Log4j2 YAML Configuration File Example

    But if you want to configure Log4j2 and control it from your Java class, Log4j2 provides multiple classes in its config package org.apache.logging.log4j.core.config which is used to configure Log4j2. In this tutorial, we will cover how you can set up Console Appender, and Rolling File Appender for logging.

    Let's start by adding the dependencies.

    Log4j2 Programmatic Configuration in Java Class

    Log4j2 Dependency in POM.xml

    Make sure you have the following dependency in the pom.xml file of your project. We have covered the complete project setup steps in the tutorials listed above.

    <dependency>
    	<groupId>org.apache.logging.log4j</groupId>
    	<artifactId>log4j-api</artifactId>
    	<version>2.13.1</version>
    </dependency>
    <dependency>
    	<groupId>org.apache.logging.log4j</groupId>
    	<artifactId>log4j-core</artifactId>
    	<version>2.13.1</version>
    </dependency>

    Log4j2 Programmatic Configuration for Console Appender

    Below Java code can be used to configure Console Appender in Log4j2.

    ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
    
    builder.setStatusLevel(Level.DEBUG);
    // naming the logger configuration
    builder.setConfigurationName("DefaultLogger");
    
    // create a console appender
    AppenderComponentBuilder appenderBuilder = builder.newAppender("Console", "CONSOLE")
                    .addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT);
    // add a layout like pattern, json etc
    appenderBuilder.add(builder.newLayout("PatternLayout")
                    .addAttribute("pattern", "%d %p %c [%t] %m%n"));
    RootLoggerComponentBuilder rootLogger = builder.newRootLogger(Level.DEBUG);
    rootLogger.add(builder.newAppenderRef("Console"));
    
    builder.add(appenderBuilder);
    builder.add(rootLogger);
    Configurator.reconfigure(builder.build());

    The main classes to focus on here are:

    ConfigurationBuilder class, which is the main class that holds the default configuration of the logger. In this, we will prepare an instance of this class, configure it and then use it to reconfigure the default logger.

    AppenderComponentBuilder class is used to initialize the appender. We can use it to set Console Appender, File Appender, Rolling File Appender, etc.

    In the code above, we have added a pattern layout to the appender, and we have also specified the pattern.

    Then, we used the RootLoggerComponentBuilder class, to configure the root logger too. As we have covered in other tutorials mentioned above, log4j2 provides a default root logger, whereas we can define our own logger too.

    So we will provide the same configuration to the root logger too. And then we will reconfigure the logger using the Configurator.reconfigure function. To build the logger that we have configured, we use the build() function.

    We can change the log level using the setStatusLevel() function.

    Log4j2 Programmatic Configuration for File Appender

    To configure a File Appender, use the following code:

    String filename = "app.log";
    String pattern = "%d %p %c [%t] %m%n";
    
    ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
    
    builder.setStatusLevel(Level.DEBUG);
    builder.setConfigurationName("DefaultFileLogger");
    
    // set the pattern layout and pattern
    LayoutComponentBuilder layoutBuilder = builder.newLayout("PatternLayout")
                    .addAttribute("pattern", pattern);
    
    // create a file appender
    AppenderComponentBuilder appenderBuilder = builder.newAppender("LogToFile", "File")
                    .addAttribute("fileName", fileName)
                    .add(layoutBuilder);
    
    builder.add(appenderBuilder);
    rootLogger.add(builder.newAppenderRef("LogToFile"));
    builder.add(rootLogger);
    Configurator.reconfigure(builder.build());

    While configuring a File Appender, everything is the same except that we have provided an additional attribute fileName to specify the name of the file in which logs will be printed.

    Log4j2 Programmatic Configuration for RollingFile Appender

    Now let's see how we can configure a RollingFile Appender to use it to print logs in files and set rolling policies for these files.

    String filename = "app.log";
    String pattern = "%d %p %c [%t] %m%n";
    
    ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
    
    builder.setStatusLevel(Level.DEBUG);
    builder.setConfigurationName("DefaultRollingFileLogger");
    // specifying the pattern layout
    LayoutComponentBuilder layoutBuilder = builder.newLayout("PatternLayout")
                    .addAttribute("pattern", pattern);
    // specifying the policy for rolling file
    ComponentBuilder triggeringPolicy = builder.newComponent("Policies")
                   .addComponent(builder.newComponent("SizeBasedTriggeringPolicy").addAttribute("size", "1KB"));
    
    // create a console appender
    AppenderComponentBuilder appenderBuilder = builder.newAppender("LogToRollingFile", "RollingFile")
                    .addAttribute("fileName", fileName)
                    .addAttribute("filePattern", fileName+"-%d{MM-dd-yy-HH-mm-ss}.log.")
                    .add(layoutBuilder)
                    .addComponent(triggeringPolicy);
    
    builder.add(appenderBuilder);
    rootLogger.add(builder.newAppenderRef("LogToRollingFile"));
    builder.add(rootLogger);
    Configurator.reconfigure(builder.build());

    In the rolling file appender, we have used the LayoutComponentBuilder class to configure the pattern layout and the ComponentBuilder class to set up policies. Just like we have specified the SizeBasedTriggeringPolicy you can also set the TimeBasedTriggeringPolicy and DefaultTrigerringPolicy too.

    Main Java Class

    Here is the main Java class in which you can use any of the above appenders, for your ease, we have configured the Console and RollingFile appenders. So if we run this Java class, we get logs on the Console and in a file named app.log as well.

    import org.apache.logging.log4j.Level;
    import org.apache.logging.log4j.LogManager;
    import org.apache.logging.log4j.Logger;
    import org.apache.logging.log4j.core.appender.ConsoleAppender;
    import org.apache.logging.log4j.core.config.Configurator;
    import org.apache.logging.log4j.core.config.builder.api.AppenderComponentBuilder;
    import org.apache.logging.log4j.core.config.builder.api.ComponentBuilder;
    import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilder;
    import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilderFactory;
    import org.apache.logging.log4j.core.config.builder.api.LayoutComponentBuilder;
    import org.apache.logging.log4j.core.config.builder.api.RootLoggerComponentBuilder;
    import org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration;
    
    public class App {
    	
    	private static final Logger logger = LogManager.getLogger(App.class);
    	
    	public static void main(String[] args) {
    		
    		App.initializeYourLogger("app.log","%d %p %c [%t] %m%n");
    
    		logger.debug("Hello from Log4j 2");
    		logger.debug("This is a Debug Message!");
    		logger.info("This is an Info Message!");
    		try {
    			System.out.println(100/0);
    		}
    		catch(Exception e) {
    			logger.error("Error Occured", e);
    		}
    		//logger.error("And here comes the Error Message!", new RuntimeException("Run Run Run"));
    		
    	}
    	
    	public static void initializeYourLogger(String fileName, String pattern) {
    
            ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
    
            builder.setStatusLevel(Level.DEBUG);
            builder.setConfigurationName("DefaultLogger");
    
            // create a console appender
            AppenderComponentBuilder appenderBuilder = builder.newAppender("Console", "CONSOLE").addAttribute("target",
                    ConsoleAppender.Target.SYSTEM_OUT);
            appenderBuilder.add(builder.newLayout("PatternLayout")
                    .addAttribute("pattern", pattern));
            RootLoggerComponentBuilder rootLogger = builder.newRootLogger(Level.DEBUG);
            rootLogger.add(builder.newAppenderRef("Console"));
    
            builder.add(appenderBuilder);
    
            // create a rolling file appender
            LayoutComponentBuilder layoutBuilder = builder.newLayout("PatternLayout")
                    .addAttribute("pattern", pattern);
            ComponentBuilder triggeringPolicy = builder.newComponent("Policies")
                    .addComponent(builder.newComponent("SizeBasedTriggeringPolicy").addAttribute("size", "1KB"));
            appenderBuilder = builder.newAppender("LogToRollingFile", "RollingFile")
                    .addAttribute("fileName", fileName)
                    .addAttribute("filePattern", fileName+"-%d{MM-dd-yy-HH-mm-ss}.log.")
                    .add(layoutBuilder)
                    .addComponent(triggeringPolicy);
            builder.add(appenderBuilder);
            rootLogger.add(builder.newAppenderRef("LogToRollingFile"));
            builder.add(rootLogger);
            Configurator.reconfigure(builder.build());
        }
    
    }


    2020-04-27 21:54:28,081 DEBUG com.abhishek.log4j2.App [main] Hello from Log4j 2
    2020-04-27 21:54:28,111 DEBUG com.abhishek.log4j2.App [main] This is a Debug Message!
    2020-04-27 21:54:28,111 INFO com.abhishek.log4j2.App [main] This is an Info Message!
    2020-04-27 21:54:28,112 ERROR com.abhishek.log4j2.App [main] Error occurred
    java.lang.ArithmeticException: / by zero
    at com.abhishek.log4j2.App.main(App.java:29) [classes/:?]

    You may see some additional logs printed on the console when you run the above class, as Log4j2 classes also print logs in DEBUG mode.

    That's it for this tutorial. For complete project setup using Maven or if you want to see how you can configure Log4j2 using XML or JSON or Properties file or YAML file check out our other tutorials.

    Freqeuntly Asked Questions(FAQs)

    1. What is the use of log4j in Java?

    Log4j is a logging utility for Java applications that allows developers to easily output log statements from their code. It provides a flexible logging architecture that allows developers to log messages at different levels of severity and direct the output to different destinations, such as a file or a database.

    Log4j is widely used in enterprise applications to generate useful information for debugging, performance analysis, and auditing.

    2. How to configure log4j properties file in Java?

    To configure log4j using a properties file in Java, you can create a file named log4j.properties in your application's classpath and specify the desired configuration properties. Here's an example:

    # Set root logger level to DEBUG and send logs to console
    log4j.rootLogger=DEBUG, console
    
    # Configure console appender
    log4j.appender.console=org.apache.log4j.ConsoleAppender
    log4j.appender.console.layout=org.apache.log4j.PatternLayout
    log4j.appender.console.layout.ConversionPattern=%d{HH:mm:ss} %-5p %c{1}:%L - %m%n
    

    This configuration sets the root logger level to DEBUG and sends logs to the console. It also configures the console appender to use a PatternLayout with a specific format.

    3. How to set log level in log4j programmatically?

    To set the log level in log4j programmatically, you can use the org.apache.log4j.Logger class and call its setLevel method. Here's an example:

    import org.apache.log4j.Logger;
    
    public class MyClass {
      private static final Logger logger = Logger.getLogger(MyClass.class);
    
      public static void main(String[] args) {
        logger.setLevel(Level.INFO);
        logger.debug("This message will not be logged");
        logger.info("This message will be logged");
      }
    }
    

    4. How to set log4j properties programmatically in Java?

    To set log4j properties programmatically in Java, you can use the org.apache.log4j.PropertyConfigurator class and call its configure method with a Properties object. Here's an example:

    import org.apache.log4j.Logger;
    import org.apache.log4j.PropertyConfigurator;
    import java.util.Properties;
    
    public class MyClass {
      private static final Logger logger = Logger.getLogger(MyClass.class);
    
      public static void main(String[] args) {
        Properties props = new Properties();
        props.setProperty("log4j.rootLogger", "DEBUG, console");
        props.setProperty("log4j.appender.console", "org.apache.log4j.ConsoleAppender");
        props.setProperty("log4j.appender.console.layout", "org.apache.log4j.PatternLayout");
        props.setProperty("log4j.appender.console.layout.ConversionPattern", "%d{HH:mm:ss} %-5p %c{1}:%L - %m%n");
    
        PropertyConfigurator.configure(props);
    
        logger.debug("This message will be logged");
        logger.info("This message will also be logged");
      }
    }
    

    5. How to configure log4j 2 in Java?

    To configure Log4j 2 in Java, you can create a log4j2.xml or log4j2.properties configuration file in your application's classpath and specify the desired configuration properties.

    Here's an example of log4j2.xml configuration file:

    <?xml version="1.0" encoding="UTF-8"?>
    <Configuration status="INFO">
      <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
          <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger{36} - %msg%n" />
        </Console>
      </Appenders>
      <Loggers>
        <Root level="debug">
          <AppenderRef ref="Console" />
        </Root>
      </Loggers>
    </Configuration>
    

    This configuration sets the root logger level to debug and directs log output to the console using a PatternLayout.

    You can also programmatically configure Log4j 2 using the Configurator class. Here's an example:

    import org.apache.logging.log4j.LogManager;
    import org.apache.logging.log4j.Logger;
    import org.apache.logging.log4j.core.config.Configurator;
    
    public class MyClass {
      private static final Logger logger = LogManager.getLogger(MyClass.class);
    
      public static void main(String[] args) {
        Configurator.setLevel(logger.getName(), Level.DEBUG);
        logger.debug("This message will be logged");
        logger.info("This message will also be logged");
      }
    }
    

    This code sets the log level of the logger instance to DEBUG and logs two messages at the DEBUG and INFO levels, respectively.

    I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development. Founder @ Studytonight
    IF YOU LIKE IT, THEN SHARE IT
    Advertisement

    RELATED POSTS