Spring Boot 3 with Log4j2

Spring Boot provides several logging options, and one of the most commonly used libraries for logging is Log4j2.

Sopheaktra

Eang Sopheaktra

September 16 2024 08:59 am

0 286

Requirements

The fully fledged server uses the following:

  • Spring Framework
  • SpringBoot
  • Log4j2
  • Lombok

Dependencies

There are a number of third-party dependencies used in the project. Browse the Maven pom.xml file for details of libraries and versions used.

<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-actuator</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-log4j2</artifactId>
	</dependency>

	<dependency>
		<groupId>io.micrometer</groupId>
		<artifactId>micrometer-tracing-bridge-brave</artifactId>
		<version>1.2.2</version>
	</dependency>

	<dependency>
		<groupId>org.projectlombok</groupId>
		<artifactId>lombok</artifactId>
		<optional>true</optional>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-tomcat</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-test</artifactId>
		<scope>test</scope>
	</dependency>
</dependencies>

Building the project

You will need:

  • Java JDK 17 or higher
  • Maven 3.5.1 or higher
  • Tomcat 10.1

Clone the project and use Maven to build the server

$ mvn clean install

Why log is important on application or system?

Logging plays a crucial role in computer systems and software applications. Let’s explore why it’s so important:

  1. Debugging and Troubleshooting:

    • Logs provide a historical record of what happened in an application or system.
    • When something goes wrong (e.g., an error, unexpected behavior, or performance issue), developers and system administrators can analyze the logs to identify the root cause.
    • Detailed logs help pinpoint issues, making debugging and troubleshooting more efficient.
  2. Monitoring and Alerting:

    • Real-time monitoring relies on logs to track system health and performance.
    • By analyzing logs, monitoring tools can detect anomalies, bottlenecks, or abnormal behavior.
    • Alerts can be triggered based on specific log patterns (e.g., high CPU usage, memory leaks, or failed requests).
  3. Security and Auditing:

    • Security logs capture events related to authentication, authorization, and access control.
    • They help track user activity, detect unauthorized access, and prevent security breaches.
    • Auditing logs maintain a record of critical actions (e.g., user logins, data modifications) for compliance and accountability.
  4. Forensics and Incident Response:

    • In the event of a security incident or breach, logs become essential.
    • Investigators analyze logs to understand how an attack occurred, what data was compromised, and how to prevent future incidents.
  5. Performance Optimization:

    • Logs reveal performance bottlenecks, slow queries, and resource-intensive operations.
    • By analyzing logs, developers can optimize code, database queries, and system configurations.
  6. Capacity Planning and Scaling:

    • Logs help estimate resource requirements.
    • By analyzing historical logs, administrators can plan for capacity upgrades or scaling out infrastructure.
  7. Compliance and Legal Requirements:

    • Many industries have legal requirements for data retention and auditing.
    • Properly maintained logs ensure compliance with regulations (e.g., GDPR, HIPAA).
  8. Application Insights and Business Intelligence:

    • Logs contain valuable business data (e.g., user behavior, transactions, errors).
    • Analyzing logs can provide insights into user preferences, popular features, and revenue-generating activities.

Is it require to use log?

For sure it's require and you can't build application without logging because it'll make your life stucking with problems, issues, bugs on production. And

  1. How you know when it happened on production? 
  2. What's the problems?  
  3. Everytime with your problems is guessing? lol
  4. Or did you try to debug on production haha?
  5. One more did you try to clone db and put it to your development and try to test to find it?

These question above will not happend if your organization is restrict to protect risk on something change or deployment. I meant you will not allow to access to production, db production and everything that live for client using. The one way is asking for log file or db and find the problems that is the best solution.

Let start to config

log4j2's xml for configuration log with log4j2 such as:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="DEBUG">
    <Properties>
        <Property name="LOG_PATTERN">
            %d{yyyy-MM-dd HH:mm:ss.SSS} %5p ${hostName} --- [%X{traceId}, %X{spanId}, %t] %-40.40c{1.} : %m%n%ex
        </Property>
        <Property name="filename"> ${spring:spring.application.name}</Property>
    </Properties>
    <Appenders>
        <Console name="LogToConsole" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%X{traceId}, %X{spanId}, %t] %-5level %logger{36} - %msg%n"/>
        </Console>
        <RollingFile name="RollingFileAppender"
                     fileName="logs/${sys:filename}.log"
                     filePattern="logs/achieved/${sys:filename}-%d{dd-MM-yyyy}-%i.log">
            <PatternLayout>
                <Pattern>${LOG_PATTERN}</Pattern>
            </PatternLayout>
            <Policies>
                <OnStartupTriggeringPolicy />
                <SizeBasedTriggeringPolicy
                        size="500 MB" />
                <TimeBasedTriggeringPolicy />
            </Policies>
            <DefaultRolloverStrategy max="10" />
        </RollingFile>
    </Appenders>
    <Loggers>
        <Logger name="com.tra21.log4j2" level="debug" additivity="false">
            <AppenderRef ref="RollingFileAppender" />
            <AppenderRef ref="LogToConsole"/>
        </Logger>
        <Logger name="org.springframework.boot" level="error" additivity="false">
            <AppenderRef ref="LogToConsole"/>
        </Logger>
<!--        if you have hibernate and hikari please uncomment below-->
<!--        <Logger name="org.hibernate.SQL" level="debug">-->
<!--            <AppenderRef ref="RollingFileAppender" />-->
<!--            <AppenderRef ref="LogToConsole"/>-->
<!--        </Logger>-->
<!--        <Logger name="com.zaxxer.hikari" level="debug" >-->
<!--            <AppenderRef ref="RollingFileAppender" />-->
<!--            <AppenderRef ref="LogToConsole"/>-->
<!--        </Logger>-->
        <Root level="error">
            <AppenderRef ref="RollingFileAppender" />
            <AppenderRef ref="LogToConsole"/>
        </Root>
    </Loggers>
</Configuration>

Example log with controller to consume and log such as:

package com.tra21.log4j2.controllers;

import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/logs")
@Log4j2
public class LogController {
    @GetMapping("/info")
    public boolean logInfo(){
        log.info("log-info with this message: {}", "Information Message");
        return true;
    }
    @GetMapping("/warn")
    public boolean logWarn(){
        log.warn("log-warn with this message: {}", "Warn Message");
        return true;
    }
    @GetMapping("/error")
    public boolean logError(){
        log.error("log-error with this message: {}", "Error Message");
        return true;
    }
    @GetMapping("/debug")
    public boolean logDebug(){
        log.debug("log-debug with this message: {}", "Debug Message");
        return true;
    }
    @GetMapping("/fatal")
    public boolean logFatal(){
        log.fatal("log-fatal with this message: {}", "Fatal Message");
        return true;
    }
    @GetMapping("/trace")
    public boolean logTrace(){
        log.trace("log-trace with this message: {}", "Trace Message");
        return true;
    }
}

Summary

Download the source code for the sample application implementing logging on application. Also you will learn about log, its important, spring boot profiles configuration with log4j2, traceId and spanId with micrometer and some Log4j2 xml syntax and real example.

Comments

Subscribe to our newsletter.

Get updates about new articles, contents, coding tips and tricks.

Weekly articles
Always new release articles every week or weekly released.
No spam
No marketing, share and spam you different notification.
© 2023-2025 Tra21, Inc. All rights reserved.