DEV Community

Isaac Tonyloi - SWE
Isaac Tonyloi - SWE

Posted on

Logging in SpringBoot

In Spring Boot, logging is a crucial part of monitoring and troubleshooting an application. Loggers help you track the flow of execution, capture significant events, diagnose issues, and understand the application’s behavior at runtime.

Why Loggers are Necessary

Debugging:

Helps in identifying and fixing bugs by providing detailed runtime information.
Monitoring:

Provides insights into application performance and health.
Auditing:

Keeps track of user actions and system changes for security and compliance purposes.
Troubleshooting:
Assists in diagnosing issues by recording error messages and stack traces.
Operational Insights:

Offers operational visibility into the behavior of the application, especially in production environments.
Logging Options in Spring Boot
Spring Boot supports several logging frameworks. The most commonly used ones are:

- Java Util Logging (JUL)
- Log4j2
- Logback
By default, Spring Boot uses Logback for logging.

Configuring Loggers in Spring Boot

1. Default Configuration with Logback

Spring Boot comes with a pre-configured Logback setup, which can be customized via application.properties or application.yml:

application.properties:

logging.level.root=INFO
logging.level.com.example=DEBUG
logging.file.name=logs/spring-boot-app.log
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} - %msg%n
logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss} - %msg%n

Enter fullscreen mode Exit fullscreen mode

2. Using Log4j2

To use Log4j2 instead of Logback, you need to exclude Logback and include Log4j2 dependencies in your pom.xml:

pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-logging</artifactId>
    <scope>runtime</scope>
    <type>pom</type>
    <exclusions>
        <exclusion>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
        </exclusion>
    </exclusions>
</dependency>

Enter fullscreen mode Exit fullscreen mode

Log4j2 Configuration File (log4j2.xml):

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5level %logger{36} - %msg%n"/>
        </Console>
        <File name="File" fileName="logs/app.log">
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5level %logger{36} - %msg%n"/>
        </File>
    </Appenders>
    <Loggers>
        <Root level="info">
            <AppenderRef ref="Console"/>
            <AppenderRef ref="File"/>
        </Root>
        <Logger name="com.example" level="debug" additivity="false">
            <AppenderRef ref="Console"/>
        </Logger>
    </Loggers>
</Configuration>

Enter fullscreen mode Exit fullscreen mode

3. Using Java Util Logging (JUL)

If you prefer using Java Util Logging, include the following dependency:

pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-logging</artifactId>
</dependency>

Enter fullscreen mode Exit fullscreen mode

Logging Configuration(logging.properties):

handlers= java.util.logging.ConsoleHandler
java.util.logging.ConsoleHandler.level = FINE
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter

.level= INFO
com.example.level = FINE

Enter fullscreen mode Exit fullscreen mode

Usage in Code

To use logging in your Spring Boot application, inject the logger into your classes:

Using SLF4J (Recommended):

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class MyService {

    private static final Logger logger = LoggerFactory.getLogger(MyService.class);

    public void performTask() {
        logger.info("Performing task");
        try {
            // Task logic
        } catch (Exception e) {
            logger.error("Error occurred while performing task", e);
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Logging Levels

  • TRACE: Very detailed information, typically only enabled when diagnosing problems.
  • DEBUG: Detailed information on the flow through the system. Useful for debugging.
  • INFO: Interesting runtime events (startup/shutdown). Use this level for production messages.
  • WARN: Indicate potentially harmful situations.
  • ERROR: Error events that might still allow the application to continue running.
  • FATAL: Very severe error events that will presumably lead the application to abort

Top comments (0)