Log4j2 Composite Configuration with Spring Boot

The Unknown
2 min readJul 17, 2020

Log4j2 is one of the common logging solutions used in java. This article discusses on how to use log4j2 composite configuration in spring boot application. Slf4j is used as logging abstraction for log4j2.

Common use cases

  • In microservices world, having all logs following similar configuration helps to debug or extract information easily
  • Dealing with different log settings in dev, stage, and production environments but still following DRY principle.

Log4j2 composite configuration addresses the above use cases by giving flexibility to define multiple configuration files along with custom merge rules.

How to use composite configuration

log4j2.xml

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

log4j2-dev.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<Loggers>
<logger name="com.kishore.experiments.log4j2compositeconfiguration.Log4j2CompositeConfigurationApplication" level="debug" additivity="false">
<AppenderRef ref="Console"/>
</logger>
<root level="info">
<AppenderRef ref="Console"/>
</root>
</Loggers>
</Configuration>

In above log4j2.xml sets the root logger to error level. In the log4j2-dev.xml, root logger level is set to info and a new logger is added with debug level.

The above two files must be referenced in log4j2.component.properties. The contents of the file looks as below

log4j2.configurationFile=log4j2.xml,log4j2-dev.xml

When we run our spring boot application with above configuration root logger will be configured to info level and the new logger added will be configured to debug level.

Working code can be found in github here

Gotchas

  • Default spring boot application uses logback as default logging implementation for slf4j abstraction. Logging depdendency must be excluded from spring boot and spring boot log4j2 must be added. The configuration looks like below after modification
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dpendencies>
  • Base configuration file must be log4j2.xml. On startup spring application looks for log4j2.xml by default or file name specified in logging.config. If logging.config property is specified with file name, then composite configuration not working.

--

--