Spring Boot Tutorial

Spring Boot - Software Setup and Configuration (STS/Eclipse/IntelliJ)

Prerequisite (Spring Core Concepts)

Spring Boot Core

Spring Boot with REST API

Spring Boot with Database and Data JPA

Spring Boot with Kafka

Spring Boot with AOP

Spring Boot - Logging

Logging is a critical component of any application. Proper logging can aid in debugging, monitoring, and understanding the flow and state of an application. Spring Boot provides a default logging configuration via the Spring Boot Starter Logging, which includes the SLF4J API and its implementation Logback.

Let's explore the different facets of logging with Spring Boot:

1. Default Configuration:

With the spring-boot-starter-logging dependency (included by default with spring-boot-starter-web), Spring Boot configures Logback to log to the console and also offers a file-based logging option. By default, logs will have the format %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n.

2. Customizing Logging Level:

You can customize the logging level for your entire application or for specific packages or classes in the application.properties or application.yml file:

# Setting the global logging level
logging.level.root=WARN

# Setting the logging level for a specific package
logging.level.org.springframework.web=DEBUG
logging.level.com.example.demo=TRACE

3. Logging to a File:

To log to a file, set the logging.file or logging.path properties:

# Log to a specific file
logging.file=myapp.log

# Or, specify a directory to log in, Spring Boot will create a spring.log file inside this directory
logging.path=/var/log

4. Log Grouping:

Spring Boot 2.2+ provides the concept of log groups, which are predefined sets of loggers that can be configured together for convenience. For example:

logging.group.web=org.springframework.core.codec, org.springframework.http
logging.level.web=DEBUG

5. Customizing Log Format:

To customize the format of the log, you can define properties like:

logging.pattern.console= %d{HH:mm:ss} - %msg%n
logging.pattern.file= %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n

6. Profile-specific Logging:

You can have different logging configurations for different profiles. For example, you might want verbose logging in a development profile but concise logging in production.

Create a logback-spring.xml in src/main/resources:

<configuration>
    <include resource="org/springframework/boot/logging/logback/base.xml"/>
    <jmxConfigurator/>

    <springProfile name="development">
        <!-- configuration for development -->
    </springProfile>

    <springProfile name="production">
        <!-- configuration for production -->
    </springProfile>
</configuration>

7. JSON Logging:

For modern applications, especially those that run inside containers and are monitored by tools like the ELK stack (Elasticsearch, Logstash, Kibana), it's beneficial to log in a structured format like JSON. You can use libraries like logstash-logback-encoder to produce JSON logs.

8. Using a Different Logging System:

Though Spring Boot uses Logback by default, you can switch to another system (like Log4j2) by excluding the default logging and adding your preferred logging starter.

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

Logging configurations and setups can get complex, especially for larger applications. Still, the above guide offers an introduction and overview of the primary facets of logging with Spring Boot.

  1. Configuring logging in Spring Boot:

    • Description: Setting up logging in a Spring Boot application is crucial for monitoring and debugging. Spring Boot uses the SLF4J abstraction for logging.
    • Code:
      // Application properties for logging
      logging.level.root=INFO
      
  2. Using SLF4J and Logback in Spring Boot:

    • Description: Spring Boot defaults to SLF4J for logging and uses Logback as the default implementation. SLF4J provides a simple and flexible logging API.
    • Code:
      <!-- Dependency in pom.xml -->
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter</artifactId>
      </dependency>
      
  3. Logging levels and categories in Spring Boot:

    • Description: SLF4J supports different logging levels (e.g., DEBUG, INFO, WARN, ERROR) and allows categorizing logs by packages or classes.
    • Code:
      // Logging in a class
      import org.slf4j.Logger;
      import org.slf4j.LoggerFactory;
      
      public class MyClass {
          private static final Logger logger = LoggerFactory.getLogger(MyClass.class);
      
          public void someMethod() {
              logger.debug("Debug message");
              logger.info("Info message");
              logger.warn("Warning message");
              logger.error("Error message");
          }
      }
      
  4. Customizing log formats in Spring Boot:

    • Description: Customizing log formats allows you to structure logs according to your needs. Logback supports various format options.
    • Code:
      <!-- Logback configuration in src/main/resources/logback.xml -->
      <configuration>
          <property name="LOG_PATTERN" value="%d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n" />
          <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
              <encoder>
                  <pattern>${LOG_PATTERN}</pattern>
              </encoder>
          </appender>
          <root level="INFO">
              <appender-ref ref="STDOUT" />
          </root>
      </configuration>
      
  5. Logging with different appenders in Spring Boot:

    • Description: Logback supports various appenders, allowing you to direct logs to different outputs such as console, file, or even external systems.
    • Code:
      <!-- Logback with File Appender -->
      <appender name="FILE" class="ch.qos.logback.core.FileAppender">
          <file>logs/application.log</file>
          <encoder>
              <pattern>${LOG_PATTERN}</pattern>
          </encoder>
      </appender>
      
  6. Debugging and troubleshooting with Spring Boot logs:

    • Description: Utilizing logs for debugging involves strategically placing log statements in the code to trace the flow and values during execution.
    • Code:
      // Example of debugging with logs
      public class MyService {
          private static final Logger logger = LoggerFactory.getLogger(MyService.class);
      
          public void performOperation() {
              logger.debug("Entering performOperation method");
              // Your code logic
              logger.debug("Exiting performOperation method");
          }
      }
      
  7. Integration of logging frameworks like Log4j in Spring Boot:

    • Description: Spring Boot allows integrating other logging frameworks like Log4j if needed, although it's common to stick with the default SLF4J and Logback.
    • Code:
      <!-- Dependency for Log4j -->
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-log4j2</artifactId>
      </dependency>