Master Spring Boot Logging: From Basics to Advanced Configuration

This guide explains why logging is essential in Java, explores its various uses such as system monitoring, data collection, and audit, demonstrates how to print logs with SLF4J in Spring Boot, and provides detailed instructions for configuring log levels, persistence, file rotation, formatting, and Lombok shortcuts.

Java Tech Enthusiast
Java Tech Enthusiast
Java Tech Enthusiast
Master Spring Boot Logging: From Basics to Advanced Configuration

Log Overview

Logging is essential for diagnosing problems, auditing user actions, collecting operational metrics, and complying with regulatory audit requirements. Simple System.out.print statements are insufficient for production‑grade applications.

Typical Uses

System monitoring : record method execution time, response status, and other runtime metrics; trigger alerts when thresholds are exceeded.

Data collection : aggregate page views, unique visitors, click counts, etc., to support statistics and recommendation models.

Audit logging : retain immutable records of data modifications, deletions, and security‑relevant events for forensic analysis.

Logging in Spring Boot

Spring Boot automatically configures a logging system based on SLF4J (the facade) and Logback (the default implementation). Log entries contain timestamp, thread name, logger name, and log level, which are far richer than plain console prints.

Obtaining a Logger

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

The Logger class belongs to the org.slf4j package; importing a different package will cause compilation errors.

Logging Methods

logger.trace(...)
logger.debug(...)
logger.info(...)
logger.warn(...)
logger.error(...)
@RestController
public class LoggerController {
    private static final Logger logger = LoggerFactory.getLogger(LoggerController.class);

    @RequestMapping("/logger")
    public String logger() {
        logger.info("--------------------Log content--------------------");
        return "Print log";
    }
}

SLF4J Facade

SLF4J defines a unified API that delegates to a concrete backend such as Logback or Log4j2. Using the facade eliminates the need for multiple configuration files and allows the underlying implementation to be swapped without code changes.

Log Line Specification

Timestamp (millisecond precision)

Log level (ERROR, WARN, INFO, DEBUG, TRACE; Logback maps FATAL to ERROR)

Process ID

Thread name

Logger name (usually the fully‑qualified class name)

Log message

Log Levels

FATAL

– critical system error (mapped to ERROR in Logback) ERROR – high‑priority error that does not stop the application WARN – warning that does not affect functionality INFO – general informational messages (startup, request completion, etc.) DEBUG – detailed debugging information TRACE – very fine‑grained tracing for deep debugging

logger.trace("=====trace=====");
logger.debug("=====debug=====");
logger.info("=====info=====");
logger.warn("=====warn=====");
logger.error("=====error=====");

Log Configuration

1. Configuring Log Level

Set the desired level in application.properties or application.yml using the logging.level property.

# properties
logging.level.root=debug

# yaml
logging:
  level:
    root: debug

2. Log Persistence

Configure a file name or a directory to write logs to disk. If both logging.file.name and logging.file.path are defined, the name takes precedence.

# properties – file name
logging.file.name=logger/springboot.log

# properties – directory
logging.file.path=D:/temp

# yaml – file name
logging:
  file:
    name: logger/springboot.log

# yaml – directory
logging:
  file:
    path: D:/temp

3. Log File Rotation

Logback splits large files automatically. The default rotation size is 10 MB. Custom rotation can be defined as follows (the example uses 1 KB for demonstration):

# properties
logging.logback.rollingpolicy.file-name-pattern=${LOG_FILE}.%d{yyyy-MM-dd}.%i
logging.logback.rollingpolicy.max-file-size=1KB

# yaml
logging:
  logback:
    rollingpolicy:
      file-name-pattern: ${LOG_FILE}.%d{yyyy-MM-dd}.%i
      max-file-size: 1KB

4. Log Pattern Layout

The default console pattern is:

%clr(%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd'T'HH:mm:ss.SSSXXX}}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}

Key placeholders: %clr(...){color} – adds ANSI color. %d{...} – timestamp. %5p – log level padded to five characters. %t – thread name. %c – logger (class) name. %m or %msg – log message. %n – newline.

Simplified Logging with Lombok

Add Lombok to the project and annotate a class with @Slf4j. Lombok generates a static logger field named log, eliminating boilerplate.

@Slf4j
@RestController
public class LogController {
    public void log() {
        log.info("===========Log content===========");
    }
}
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

loggingSpring Bootlogbackslf4jLombok
Java Tech Enthusiast
Written by

Java Tech Enthusiast

Sharing computer programming language knowledge, focusing on Java fundamentals, data structures, related tools, Spring Cloud, IntelliJ IDEA... Book giveaways, red‑packet rewards and other perks await!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.