Standardizing Log4j2 Configuration with a Shared JAR and SpringBoot Environment Mapping

This article describes how the architecture team packages a unified log4j2.xml into a common JAR, uses sys system variables for customizable parameters, and maps SpringBoot application.yml settings to those variables via a custom EnvironmentPostProcessor, enabling developers to configure logging with minimal effort.

Zhuanzhuan Tech
Zhuanzhuan Tech
Zhuanzhuan Tech
Standardizing Log4j2 Configuration with a Shared JAR and SpringBoot Environment Mapping

Background : Although the company uses Log4j2 uniformly, each business line maintains its own log4j2 configuration file, leading to inconsistencies and errors, especially when copying configurations. Frequent updates to the company’s logging standards also make upgrades costly.

To address this, the architecture department encapsulated a standard log4j2.xml into a shared JAR, allowing developers to make simple modifications via application.yml. This encapsulation is a recommendation, not a strict requirement; custom configurations remain possible.

Solution Overview :

The shared JAR zzarch-log-common contains the log4j2.xml and supports business‑specific parameters such as service name, log path, and log level through sys system variables.

Developers only need to add the JAR as a dependency and add a few entries in application.yml to use the standardized configuration.

Package Structure and Sample Configuration :

<Properties>
    <property name="app_name">${sys:logging.zz.app-name:-unknown}</property>
    <property name="log_pattern">%d{MM-dd HH:mm:ss.SSS} %X{TRACE_ID}-%X{SPAN_ID}-%X{SAMPLED} %t %p %C{1.}:%L - %m%n</property>
    <property name="log_home">${sys:logging.zz.directory:-/opt/log/unknown}/${app_name}</property>
</Properties>

<AsyncRoot level="${sys:logging.zz.root.level:-INFO}" includeLocation="true">
    <AppenderRef ref="CONSOLE" level="${sys:logging.zz.console.level:-OFF}"/>
    <AppenderRef ref="DEBUG" level="${sys:logging.zz.debug.level:-OFF}"/>
    <AppenderRef ref="INFO"/>
    <AppenderRef ref="WARN"/>
    <AppenderRef ref="ERROR"/>
</AsyncRoot>

The configuration reads custom values from sys variables, leveraging Log4j2’s lookup mechanism.

Why Not Use SpringBoot Lookups Directly? Two reasons: (1) Using log4j-spring-cloud-config-client adds unnecessary weight, and (2) some services do not run on SpringBoot, making sys variables more universal.

Mapping SpringBoot Environment Variables to Sys Variables : The team implements an EnvironmentPostProcessor that reads properties from application.yml and sets corresponding sys system properties. The processor’s order is set later than ConfigFileApplicationListener so it runs after SpringBoot has loaded the environment.

public class LoggingEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered {
    private int order = 0;

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        String configKey = "logging.config";
        String config = environment.getProperty(configKey);
        if (!Objects.equals(config, "classpath:zzarch/log4j2.xml")) {
            return;
        }
        System.setProperty(configKey, config);

        String appName = environment.getProperty("logging.zz.app-name");
        if (Objects.nonNull(appName)) {
            System.setProperty(appNameKey, appName);
        }
        String directory = environment.getProperty("logging.zz.directory");
        if (Objects.nonNull(directory)) {
            System.setProperty(directoryKey, directory);
        }
        // ... other mappings
    }

    @Override
    public int getOrder() {
        return order;
    }
}

With this processor, values defined in application.yml are automatically available to the shared log4j2.xml via sys lookups.

How Developers Use It : Add the following snippet to application.yml and remove any existing log4j2.xml from the project.

logging:
  config: classpath:zzarch/log4j2.xml
  zz: # custom extensions
    app-name: myapp # defaults to unknown
    directory: /opt/log/zzweb # defaults to /opt/log/unknown

Conclusion :

The architecture team provides a common JAR containing a configurable log4j2.xml that uses sys variables for business‑specific settings.

The LoggingEnvironmentPostProcessor maps SpringBoot application.yml properties to those sys variables.

Developers only need to add the JAR and a few lines in application.yml to adopt the standardized logging configuration.

This approach dramatically reduces the effort required to configure Log4j2, ensures consistent formatting for easier troubleshooting, and simplifies bulk updates when logging standards evolve.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaSpringBootlog4j2
Zhuanzhuan Tech
Written by

Zhuanzhuan Tech

A platform for Zhuanzhuan R&D and industry peers to learn and exchange technology, regularly sharing frontline experience and cutting‑edge topics. We welcome practical discussions and sharing; contact waterystone with any questions.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.