Spring Boot 3 with Logback

Spring Boot provides several logging options, and one of the most commonly used libraries for logging is Logback. Logback is the default logging framework when you use Spring Boot starters.

Sopheaktra

Eang Sopheaktra

April 20 2024 12:46 am

0 632

This example explained about spring boot 3 with Logback which's come with spring boot starter:

  • Spring Boot provides several logging options, and one of the most commonly used libraries for logging is Logback.
  • Logback is the default logging framework when you use Spring Boot starters.
  • It’s essential to understand how logging works in Spring Boot to effectively manage your application’s logs.

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?

Answer me if you are in these above question. No worry I have been do like above question before when I am just start development and the first start alway like this hahahaha.

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.

In Spring Boot is zero configuration logging?

Sure because spring boot is auto configuration and already implement default logging for us like below:

  1. Spring Boot simplifies logging configuration. The only mandatory dependency is Apache Commons Logging.
  2. If you’re using Spring 4.x (Spring Boot 1.x), you need to import spring-jcl. However, Spring Boot 2.x already provides it through starters (e.g., spring-boot-starter-web).
  3. By default, Spring Boot uses Logback for logging. It preconfigures patterns and ANSI colors to make standard output more readable.
  4. The default logging level is INFO, meaning that TRACE and DEBUG messages are not visible. To activate them without changing the configuration, you can pass --debug or --trace arguments on the command line when running your application.

Log Level

  1. TRACE:

    • The lowest log level.
    • Used for very detailed information, typically useful for debugging.
    • Provides information about the flow of the application, method calls, and variable values.
    • Rarely enabled in production due to its verbosity.
  2. DEBUG:

    • Used for debugging purposes.
    • Provides detailed information about the application’s internal state.
    • Useful for diagnosing issues during development.
    • Should be disabled in production to avoid performance overhead.
  3. INFO:

    • Default log level in most applications.
    • Provides information about normal application behavior.
    • Useful for tracking important events (e.g., application startup, successful requests).
    • Enabled in production to monitor application health.
  4. WARN:

    • Indicates a potential issue or unexpected behavior.
    • Not an error, but something that might need attention.
    • Useful for catching issues before they become critical.
  5. ERROR:

    • Indicates a serious problem that prevents the application from functioning correctly.
    • Typically logged when an exception occurs or an operation fails.
    • Requires immediate attention.
  6. FATAL (not always present in all logging frameworks):

    • The highest log level.
    • Indicates a critical error that leads to application termination.
    • Rarely used, as most applications handle errors gracefully without terminating.

Requirements

The fully fledged server uses the following:

  • Spring Framework
  • SpringBoot
  • 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>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-actuator</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>

Custom Configuration

  • You can customize Logback by creating a configuration file named logback-spring.xml or logback.xml in the classpath.
  • Spring Boot recommends using the -spring variant (e.g., logback-spring.xml) over the plain ones.
  • Here’s a simple example of a logback-spring.xml configuration with condition of spring boot profiles:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <springProperty scope="context" name="name" source="spring.application.name"/>
    <property name="LOG_FILE" value="logs/${name:-LogFile}" />

    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${LOG_FILE:-}.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <!-- daily rollover -->
            <fileNamePattern>${LOG_FILE:-}.%d{yyyy-MM-dd}.%i.gz</fileNamePattern>
            <springProfile name="!prod">
                <maxFileSize>50MB</maxFileSize>
            </springProfile>
            <springProfile name="prod">
                <maxFileSize>500MB</maxFileSize>
            </springProfile>
            <!-- keep 7 days' worth of history capped at 1GB total size -->
            <maxHistory>7</maxHistory>
            <totalSizeCap>1GB</totalSizeCap>
        </rollingPolicy>
        <!--        <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">-->
        <!--            <fileNamePattern>${LOG_FILE:-}.%d{yyyy-MM-dd}.%i.gz</fileNamePattern>-->
        <!--            <minIndex>1</minIndex>-->
        <!--            <maxIndex>10</maxIndex>-->
        <!--        </rollingPolicy>-->
        <!--        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">-->
        <!--            <maxFileSize>1KB</maxFileSize>-->
        <!--        </triggeringPolicy>-->
        <encoder>
            <pattern>%d{dd-MM-yyyy HH:mm:ss.SSS} [%thread, ${name:-}, %X{traceId:--}, %X{spanId:--}] %-5level %logger{36}.%M - %msg%n</pattern>
        </encoder>
    </appender>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>
                %d{dd-MM-yyyy HH:mm:ss.SSS} %magenta([%thread, ${name:-}, %X{traceId:--}, %X{spanId:--}]) %highlight(%-5level) %logger{36}.%M - %msg%n
            </pattern>
        </encoder>
    </appender>

    <logger name="com.tra21.logback" level="debug" additivity="false">
        <appender-ref ref="STDOUT"/>
        <springProfile name="prod">
            <appender-ref ref="FILE"/>
        </springProfile>
    </logger>
<!--    <logger name="org.hibernate.SQL" level="debug" additivity="false">-->
<!--        <appender-ref ref="STDOUT"/>-->
<!--        <springProfile name="!prod">-->
<!--            <appender-ref ref="FILE"/>-->
<!--        </springProfile>-->
<!--    </logger>-->
<!--    <logger name="com.zaxxer.hikari" level="debug" additivity="false">-->
<!--        <appender-ref ref="STDOUT"/>-->
<!--        <springProfile name="prod">-->
<!--            <appender-ref ref="FILE"/>-->
<!--        </springProfile>-->
<!--    </logger>-->

    <root level="info">
        <appender-ref ref="STDOUT"/>
    </root>
</configuration>

After that logback-spring.xml is create and patse the above code you will strange on my traceId and spanId. You will know about new update on spring boot will auto have "correlation ID" for all the logs relating to one HTTP transaction as long as micrometer tracing is enabled so that why my above dependencies management has micrometer. Also I'm create controller for testing with my log and check how its work.

package com.tra21.logback.controllers;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/logs")
@Slf4j
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("/trace")
    public boolean logTrace(){
        log.trace("log-trace with this message: {}", "Trace Message");
        return true;
    }
}

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

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 logback, traceId and spanId with micrometer and some logback 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.