Configure Log4j loggers programmatically

Build a Log4j 2 configuration in code, distinguish initialization from reconfiguration, and recognize the limits of legacy Log4j 1.x APIs.

Best practices
Configure Log4j loggers programmatically

Log4j 2 provides ConfigurationBuilderFactory for building a configuration and Configurator for applying it to a logger context. Keep ordinary production settings in a configuration file when that makes them easier to operate; programmatic configuration is useful for tests and configurations assembled at runtime.

Configure Log4j 2

This method uses Log4j API and Core. Invoke it during application startup, before other code initializes logging:

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.config.Configurator;
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.impl.BuiltConfiguration;

public class LoggingSetup {
    public static void initialize() {
        ConfigurationBuilder<BuiltConfiguration> builder =
            ConfigurationBuilderFactory.newConfigurationBuilder();
        builder.add(builder.newAppender("Stdout", "Console")
            .add(builder.newLayout("PatternLayout")
                .addAttribute("pattern", "%d %-5p [%t] %m%n")));
        builder.add(builder.newRootLogger(Level.INFO)
            .add(builder.newAppenderRef("Stdout")));
        Configurator.initialize(builder.build(false));
        Logger log = LogManager.getLogger(LoggingSetup.class);
        log.info("Programmatic logging configuration is active");
    }
}

If you intend to replace an already active configuration, use Configurator.reconfigure(configuration). Calling initialize() later does not establish a universal “last initialization wins” rule. Loggers and contexts may already have been created by framework startup.

Recognize Log4j 1.x code in legacy systems

Log4j 1.x has reached end of life. The following is a legacy API example, not a recommendation for a new application:

// Option 1: a basic console appender
org.apache.log4j.BasicConfigurator.configure();

// Option 2: configure a file appender instead of Option 1
org.apache.log4j.Logger root = org.apache.log4j.Logger.getRootLogger();
root.setLevel(org.apache.log4j.Level.INFO);
root.addAppender(new org.apache.log4j.FileAppender(
    new org.apache.log4j.PatternLayout("%d %-5p %m%n"), "app.log"));

The FileAppender constructor can throw IOException; the surrounding method must catch or declare it. Running both options installs both appenders. These org.apache.log4j classes cannot be substituted for Log4j 2's org.apache.logging.log4j classes without a migration plan.

Frequently asked questions

Does code override log4j2.xml?

That depends on how and when the active context is configured. Initialize before logging begins, or explicitly reconfigure the intended context. Do not depend on an assumed ordering between unrelated initialization calls.

How can a test silence logging?

Temporarily setting the root level to OFF silences loggers that inherit that level. Loggers with explicit levels can still emit events. Use an isolated test configuration that also covers those loggers, then restore the prior configuration after the test.

See the Log4j programmatic configuration guide.

Get a tailored plan

Contact us

Join the community

Scan with WeChat
to join the community

Try Guance

Start online and pay only for what you use.

Get started

Choose a Guance plan

Code hosting