DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4
  • How Spring Boot Starters Integrate With Your Project
  • A Practical Guide to Creating a Spring Modulith Project
  • Structured Logging in Spring Boot 3.4 for Improved Logs

Trending

  • Tired of Spring Overhead? Try Dropwizard for Your Next Java Microservice
  • The Smart Way to Talk to Your Database: Why Hybrid API + NL2SQL Wins
  • How To Build Resilient Microservices Using Circuit Breakers and Retries: A Developer’s Guide To Surviving
  • Vibe Coding With GitHub Copilot: Optimizing API Performance in Fintech Microservices
  1. DZone
  2. Coding
  3. Frameworks
  4. A Guide To Spring Boot Log4J2 Configuration With Examples

A Guide To Spring Boot Log4J2 Configuration With Examples

In this article, we look at the various Log4J2 Configuration options that can be used with Spring Boot

By 
Saurabh Dashora user avatar
Saurabh Dashora
DZone Core CORE ·
Jul. 07, 21 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
21.5K Views

Join the DZone community and get the full member experience.

Join For Free

In this post, we will look at Spring Boot Log4J2 configuration examples. 

This will build up from the previous post about the basic Spring Boot Log4J2 setup and therefore, it would be good to read this post after the first one.

In the previous post, we had completed Log4J2 setup using basic parameters in the application.properties. The same setup can also be done using XML, YAML, or JSON.

1. Spring Boot Log4J2 XML Configuration

To configure Log4J2 using XML, we need to create a file named log4j2.xml in the resources folder of our application.

XML
 
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorInterval="30">
    <Properties>
        <Property name="LOG_PATTERN">
            %d{yyyy-MM-dd HH:mm:ss.SSS} %5p ${hostName} --- [%15.15t] %-40.40c{1.} : %m%n%ex
        </Property>
    </Properties>
    <Appenders>
        <Console name="ConsoleAppender" target="SYSTEM_OUT" follow="true">
            <PatternLayout pattern="${LOG_PATTERN}"/>
        </Console>
    </Appenders>
    <Loggers>
        <Logger name="com.progressivecoder.loggingdemo" level="debug" additivity="false">
            <AppenderRef ref="ConsoleAppender" />
        </Logger>

        <Root level="info">
            <AppenderRef ref="ConsoleAppender" />
        </Root>
    </Loggers>
</Configuration>

The important things to note here are as follows:

  • First, we are defining a pattern for our logs. This is basically meant to transform how the logs should appear. As you can see, we have the timestamp of the log, hostname, and the actual log details in the pattern
  • Next, we have the Appenders section. In this section, we define the ConsoleAppender and set the PatternLayout property to point to LOG_PATTERN.
  • After this, we have the Loggers section. In this section, we define the different types of Log Levels we want to use for a particular package. As you can see, we use the Log Level DEBUG for com.progressivecoder.loggingdemo package. Also, we link it to the Appender known as ConsoleAppender. This sends all logs of DEBUG level from this package to the console.
  • We also have a Root level Logger. It sends all logs with Log Level INFO to the console.

2. Spring Boot Log4J2 YAML Configuration

In order to use YAML for configuring Spring Boot Log4J2, we need to have additional packages in our application. The packages are jackson-dataformat-yaml and jackson-databind.

Below are the updates in the POM.xml.

XML
 
<dependency>
			<groupId>com.fasterxml.jackson.dataformat</groupId>
			<artifactId>jackson-dataformat-yaml</artifactId>
			<version>2.11.3</version>
</dependency>
<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.11.3</version>
</dependency>

Next, we create a file with the name log4j2.yml in the resources folder of our application. Below are the contents of the file. 

YAML
 
Configutation:
  name: Default
  Properties:
    Property:
      name: log_pattern
      value: "%d{yyyy-MM-dd HH:mm:ss.SSS} %5p ${hostName} --- [%15.15t] %-40.40c{1.} : %m%n%ex"
  Appenders:
    Console:
      name: Console_Appender
      target: SYSTEM_OUT
      PatternLayout:
        pattern: ${log_pattern}
  Loggers:
    Logger:
      - name: com.progressivecoder.loggingdemo
        level: debug
        additivity: false
        AppenderRef:
          - ref: Console_Appender
    Root:
      level: info
      AppenderRef:
        - ref: Console_Appender

The above configuration basically does the same thing as the previous XML configuration. 

3. Spring Boot Log4J2 JSON Configuration

We can also configure Log4J2 using JSON. To do so first, we update the POM.xml to include the below Jackson dependencies.

XML
 
<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>2.11.3</version>
</dependency>
<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.11.3</version>
</dependency>
<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-annotations</artifactId>
			<version>2.11.3</version>
</dependency>

Next, we create a file name log4j2.json in the resources folder and define the configuration in that file. See below: 

JSON
 
{
  "configuration": {
    "name": "Default",
    "properties": {
      "property": [
        {
          "name": "log_pattern",
          "value": "%d{yyyy-MM-dd HH:mm:ss.SSS} %5p ${hostName} --- [%15.15t] %-40.40c{1.} : %m%n%ex"
        }
      ]
    },
    "appenders": {
      "Console": {
        "name": "Console-Appender",
        "target": "SYSTEM_OUT",
        "PatternLayout": {
          "pattern": "${log_pattern}"
        }
      }
    },
    "loggers": {
      "logger": {
        "name": "com.progressivecoder.loggingdemo",
        "level": "debug",
        "additivity" : "false",
        "appender-ref": [{"ref": "Console-Appender"}]
      },
      "root": {
        "level": "info",
        "appender-ref": {"ref": "Console-Appender"}
      }
    }
  }
}

This configuration also does the same thing as the XML and the YAML configurations respectively.


With this, we have looked at various ways of performing Spring Boot Log4J2 Configuration. To be specific, we basically configured the Log4J2 settings using XML, YAML, and JSON formats. The code for the XML configuration is available in Github. 

In the next post, we will look at File Appenders in Spring Boot Log4J2.

Spring Framework Spring Boot

Published at DZone with permission of Saurabh Dashora. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4
  • How Spring Boot Starters Integrate With Your Project
  • A Practical Guide to Creating a Spring Modulith Project
  • Structured Logging in Spring Boot 3.4 for Improved Logs

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!