Mastering Spring Boot Logging: Levels, Persistence, Formatting, and Lombok Simplification
This article explains why traditional System.out printing is insufficient, introduces Spring Boot's built‑in SLF4J/Logback logging, demonstrates how to obtain and use a logger, details log levels, configuration of log levels, file persistence, rolling policies, formatting, and shows how Lombok's @Slf4j annotation can simplify logger usage.
Logging is essential for diagnosing and monitoring Java applications; while System.out.print can display messages, it lacks the structure, configurability, and persistence needed for production systems. As projects grow, developers often need to record audit trails, collect usage data for analytics, and comply with security regulations, which requires a dedicated logging framework.
Spring Boot Logging Basics
When a Spring Boot application starts, it automatically configures SLF4J with Logback as the underlying implementation. Unlike raw System.out output, SLF4J provides richer information such as timestamps, thread names, logger names, and log levels.
Obtaining a Logger
Use LoggerFactory.getLogger(YourClass.class) to create a logger tied to a specific class, which helps pinpoint the source of a log entry. The logger belongs to the org.slf4j package.
private static Logger logger = LoggerFactory.getLogger(LoggerController.class);Log messages are emitted via methods that correspond to the defined levels:
logger.trace("=====trace=====");
logger.debug("=====debug=====");
logger.info("=====info=====");
logger.warn("=====warn=====");
logger.error("=====error=====");Facade Pattern of SLF4J
SLF4J acts as a facade, offering a uniform API while delegating the actual logging work to a concrete implementation (e.g., Logback, Log4j). This decouples application code from specific logging libraries, reducing dependency conflicts and simplifying future replacements.
Log Levels
Spring Boot defines six levels, ordered from most severe to least: FATAL: critical system‑level error requiring immediate attention. ERROR: high‑priority error that does not halt the application. WARN: potential issue that warrants monitoring. INFO: normal operational messages such as startup or request completion. DEBUG: detailed information useful during debugging. TRACE: fine‑grained tracing, finer than DEBUG.
Logback does not have a native FATAL level; it maps to ERROR. Developers choose the appropriate level to filter logs and reduce noise.
Configuring Log Levels
Set the desired level in application.properties or application.yml using the logging.level key. Example: logging.level.root=debug or
logging:
level:
root: debugLog Persistence
To retain logs beyond the console, configure a file name and/or directory.
Properties: logging.file.name=logger/springboot.log YAML:
logging:
file:
name: logger/springboot.logDirectory (Properties): logging.file.path=D:/temp Directory (YAML):
logging:
file:
path: D:/tempIf both name and path are set, the name takes precedence.
Log File Rolling
Logback automatically splits files that exceed a size threshold (default 10 MB). Custom rolling can be defined, for example to split at 1 KB for demonstration:
logging.logback.rollingpolicy.file-name-pattern=${LOG_FILE}.%d{yyyy-MM-dd}.%i
logging.logback.rollingpolicy.max-file-size=1KBThe resulting files follow the pattern logname.YYYY‑MM‑DD.index.
Log Formatting
The output format for console and file logs is configurable via logging.pattern.console and logging.pattern.file. Place‑holders include: %d{...}: timestamp (millisecond precision). %5p: log level. %t or %thread: thread name. %c: fully‑qualified logger name. %m / %msg: log message. %n: newline. %clr(...){color}: optional color styling for console output.
Example console pattern (default):
%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}Simplifying Logger Injection with Lombok
Adding Lombok to the project and annotating a class with @Slf4j automatically creates a static logger named log, removing the need for explicit LoggerFactory calls.
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency> @Slf4j
@RestController
public class LogController {
public void log() {
log.info("===========Custom log content===========");
}
}Conclusion
Effective logging in Spring Boot involves understanding the purpose of logs, selecting appropriate levels, configuring persistence and rolling policies, customizing output formats, and optionally using Lombok to reduce boilerplate. Properly configured logs enable rapid problem discovery, system monitoring, data collection for analytics, and audit compliance.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
