Logging
Spring Boot comes with logging already wired up: your code writes through the SLF4J API and Logback does the actual output. You get coloured console logs out of the box, can change levels per package with a property, write to files, and — since Boot 3.4 — switch to structured JSON logs with one line of configuration.
Writing log messages
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Service
class TaskService {
private static final Logger log = LoggerFactory.getLogger(TaskService.class);
Task complete(long id) {
log.debug("Completing task {}", id);
Task task = repository.findById(id).orElseThrow();
if (task.done()) {
log.warn("Task {} was already done", id);
}
log.info("Task {} '{}' completed", id, task.title());
return task.withDone(true);
}
}Use {} placeholders instead of string concatenation: the message is only formatted if the level is enabled, so disabled debug calls cost almost nothing. Pass an exception as the last argument to get its stack trace: log.error("Import failed for {}", file, ex).
Log levels
| Level | Use for |
|---|---|
ERROR |
something failed and needs attention |
WARN |
unexpected but handled; might become a problem |
INFO |
important business events, startup/shutdown (the default threshold) |
DEBUG |
detail useful while developing or diagnosing |
TRACE |
very fine-grained detail |
A logger prints a message only if the message's level is at least the configured level. This program shows the rule and SLF4J-style {} formatting:
import java.util.List;
class MiniLogger {
static final List<String> LEVELS = List.of("TRACE", "DEBUG", "INFO", "WARN", "ERROR");
private final String name;
private final String threshold;
MiniLogger(String name, String threshold) { this.name = name; this.threshold = threshold; }
void log(String level, String pattern, Object... args) {
if (LEVELS.indexOf(level) < LEVELS.indexOf(threshold)) return; // filtered out
StringBuilder msg = new StringBuilder();
int argIndex = 0;
for (int i = 0; i < pattern.length(); i++) {
if (pattern.startsWith("{}", i) && argIndex < args.length) {
msg.append(args[argIndex++]);
i++;
} else {
msg.append(pattern.charAt(i));
}
}
System.out.printf("%5s %s : %s%n", level, name, msg);
}
}
class Main {
public static void main(String[] args) {
for (String threshold : List.of("INFO", "DEBUG")) {
System.out.println("-- level " + threshold + " --");
MiniLogger log = new MiniLogger("c.e.tasks.TaskService", threshold);
log.log("DEBUG", "Completing task {}", 7);
log.log("INFO", "Task {} '{}' completed", 7, "Write docs");
log.log("WARN", "Task {} was already done", 7);
}
}
}-- level INFO --
INFO c.e.tasks.TaskService : Task 7 'Write docs' completed
WARN c.e.tasks.TaskService : Task 7 was already done
-- level DEBUG --
DEBUG c.e.tasks.TaskService : Completing task 7
INFO c.e.tasks.TaskService : Task 7 'Write docs' completed
WARN c.e.tasks.TaskService : Task 7 was already done
Configuring levels
Levels are set per logger name — normally a package or class — in application.properties:
logging.level.root=INFO
logging.level.com.example.tasks=DEBUG
logging.level.org.springframework.web=DEBUG
logging.level.org.hibernate.SQL=DEBUGA logger inherits the level of its closest configured parent package: with the settings above, com.example.tasks.task.TaskService logs at DEBUG, org.apache.catalina at INFO.
You can also change a level at runtime through Actuator, without restarting:
curl -s -X POST localhost:8080/actuator/loggers/com.example.tasks \
-H "Content-Type: application/json" -d '{"configuredLevel":"DEBUG"}' -w "%{http_code}\n"
curl -s localhost:8080/actuator/loggers/com.example.tasks204
{"configuredLevel":"DEBUG","effectiveLevel":"DEBUG"}
(Requires spring-boot-starter-actuator and exposing the loggers endpoint — see the Actuator lesson.)
Reading the default console format
2025-10-16T10:15:42.118+07:00 INFO 51544 --- [tasks] [nio-8080-exec-1] c.e.tasks.task.TaskService : Task 7 'Write docs' completed| Part | Meaning |
|---|---|
2025-10-16T10:15:42.118+07:00 |
timestamp with offset |
INFO |
level |
51544 |
process id |
[tasks] |
spring.application.name |
[nio-8080-exec-1] |
thread — here a Tomcat request thread |
c.e.tasks.task.TaskService |
logger name, abbreviated to fit |
after : |
the message |
Log files
logging.file.name=logs/tasks.log
logging.logback.rollingpolicy.max-file-size=10MB
logging.logback.rollingpolicy.max-history=7Boot then writes to the console and the file, rolling it over at 10 MB and keeping 7 archives.
Structured (JSON) logging
Log platforms such as Elasticsearch, Loki or Datadog prefer one JSON object per line. Spring Boot 3.4+ supports this natively:
logging.structured.format.console=ecs./mvnw -q spring-boot:run | grep "completed"{"@timestamp":"2025-10-16T03:15:42.118Z","log":{"level":"INFO","logger":"com.example.tasks.task.TaskService"},"process":{"pid":51544,"thread":{"name":"http-nio-8080-exec-1"}},"service":{"name":"tasks"},"message":"Task 7 'Write docs' completed","ecs":{"version":"8.11"}}
Supported formats are ecs (Elastic Common Schema), gelf (Graylog) and logstash.
Tip: Never log passwords, tokens or full personal data. Log identifiers (
task 7,user 42) instead of whole objects, and be careful withtoString()of entities that may contain sensitive fields.
Test yourself
Why prefer log.debug("Task {}", id) over log.debug("Task " + id)?
- It is shorter to type
- The message is only built if DEBUG is enabled
- Concatenation is not allowed in SLF4J
- It logs at a higher level
The configured level is WARN. Which messages appear?
- DEBUG and above
- INFO and above
- WARN and ERROR
- Only ERROR
Which property turns on JSON console logs in Spring Boot 3.4+?
logging.json=truelogging.structured.format.console=ecslogging.pattern.console=jsonspring.logging.format=json