Sub topic 1
Why Logging Matters and What to Log
Prerequisites
This chapter assumes basic Java, a simple Spring Boot application, Maven or Gradle, and familiarity with application.properties. It also assumes you know that Spring profiles select environment-specific settings.
Logging records events while an application runs. Logs help you diagnose failures, understand important business actions, and measure behavior after deployment. A useful log answers four questions:
- What happened?
- When did it happen?
- Which operation or request was involved?
- What information is needed to investigate it?
Log state changes, failed operations, important external calls, and security-relevant events. Do not log passwords, access tokens, payment data, or unnecessary personal information.
How Spring Boot logging is assembled: SLF4J and Logback
Spring Boot’s standard web starter includes spring-boot-starter-logging. It brings in SLF4J and Logback.
SLF4J is a logging facade: a common Java API that application code calls. Logback is the default logging implementation that formats and sends those messages to destinations such as the console or a file. This separation lets application code avoid depending directly on one logging backend.
Understanding log levels
A log level describes the importance of an event. From least to most severe, the common levels are TRACE, DEBUG, INFO, WARN, and ERROR.
Use DEBUG for diagnostic detail, INFO for normal milestones, WARN for recoverable problems, and ERROR when an operation fails. TRACE is more detailed than DEBUG and is usually enabled briefly. A configured threshold filters out messages below that level. For example, an INFO threshold keeps INFO, WARN, and ERROR, but hides DEBUG.
Writing log statements with parameterized messages
Create one logger per class. SLF4J uses {} placeholders. The values are supplied separately, so the message is formatted only when the level is enabled.
private static final Logger log =
LoggerFactory.getLogger(OrderService.class);
log.info("Placing order {} with {} items", orderId, items);
log.error("Order {} failed", orderId, exception);Pass an exception as the final argument when you need its stack trace. Avoid string concatenation because it performs work even when the message is filtered.
Exercise
Which level should normally record a failed order, and how should its exception be passed?
Show answer
Use ERROR and pass the exception as the final argument to the parameterized logging call.