Logging in Spring Boot
Logging in Spring Boot works out of the box: every application starts with SLF4J as the logging API, Logback as the logging engine, a readable console format and sensible log levels. Good logs are still something you design. You decide what to log at which level, where the logs go, how they are formatted for your log platform, and how to follow one request through thousands of lines.
This tutorial explains how Spring Boot's logging is put together, how to set levels per package and with log groups, how to write log files with rotation, how to switch to JSON structured logs for tools such as Elasticsearch or Loki, how to add a correlation ID to every line with MDC, and how to change log levels at runtime without a restart.
1. How Logging in Spring Boot Works
Logging in Java has two layers, and Spring Boot sets up both:
- The logging API is what your code calls. Spring Boot uses SLF4J (Simple Logging Facade for Java), a thin interface with methods such as
log.info(...). - The logging backend decides what happens to each message: which messages are kept, how they are formatted and where they are written. The default backend is Logback; Log4j2 is the main alternative.
Every starter brings spring-boot-starter-logging, which contains Logback plus bridges that route other logging APIs (java.util.logging, Log4j API, Apache Commons Logging) into SLF4J. So libraries that use different APIs all end up in the same log output. Spring Boot's LoggingSystem then configures the backend from your logging.* properties, very early during startup.
2. Writing Log Messages with SLF4J
Create one logger per class and use placeholders ({}) instead of string concatenation. The message is only built if the level is enabled, and the last argument can be an exception, which prints its stack trace.
private static final Logger log = LoggerFactory.getLogger(PaymentService.class);
public void charge(String orderId, BigDecimal amount) {
log.debug("Charging order {} amount {}", orderId, amount); // details for developers
try {
gateway.charge(orderId, amount);
log.info("Payment captured for order {}", orderId); // business event
} catch (GatewayTimeoutException ex) {
log.warn("Payment gateway timed out for order {}, will retry", orderId);
throw ex;
} catch (RuntimeException ex) {
log.error("Payment failed for order {}", orderId, ex); // exception last: stack trace
throw ex;
}
}
SLF4J 2 also has a fluent API that can attach key-value pairs, which structured JSON logging (section 6) turns into separate fields:
log.atInfo()
.setMessage("Payment captured")
.addKeyValue("orderId", orderId)
.addKeyValue("amount", amount)
.log();
3. Log Levels and How to Set Them
| Level | Use for | Example |
|---|---|---|
ERROR | A failure that needs attention | Payment failed, message could not be processed |
WARN | Something unexpected the application recovered from | Retrying a timed-out call, falling back to a default |
INFO | Important business and lifecycle events | Order placed, application started |
DEBUG | Details useful when investigating a problem | Input values, decisions taken |
TRACE | Very detailed, step-by-step information | Every SQL parameter, every loop iteration |
The root level is INFO, so DEBUG and TRACE messages are dropped unless you lower the level. Set levels per package with logging.level.<package>:
logging.level.root=INFO
logging.level.com.javabytechie.shop=DEBUG
logging.level.org.springframework.web=WARN
Like any property, a level can also come from an environment variable (LOGGING_LEVEL_COM_JAVABYTECHIE_SHOP=DEBUG) or a command-line argument. Starting with --debug switches on debug output for a selection of core loggers, such as the embedded container and Hibernate, without making your whole application verbose.
3.1 Log Groups
A log group gives several packages one name, so you can change them together. Spring Boot predefines two: web (Spring MVC and related packages) and sql (Spring JDBC and Hibernate SQL logging).
logging.group.checkout=com.javabytechie.shop.order,com.javabytechie.shop.payment
logging.level.checkout=DEBUG
logging.level.sql=DEBUG
3.2 Levels per Environment
Put noisy levels in a development profile file such as application-dev.properties, so production stays at INFO. See Spring Boot profiles.
4. Reading the Default Log Format
2026-12-04T10:15:42.318+05:30 INFO 48213 --- [shop] [nio-8080-exec-3] c.j.shop.order.OrderService : Order ORD-1001 placed for 2 items
| Part | Meaning |
|---|---|
2026-12-04T10:15:42.318+05:30 | Date and time with millisecond precision and time zone offset |
INFO | Log level |
48213 | Process ID |
--- | Separator before the actual log content |
[shop] | Application name from spring.application.name (hide it with logging.include-application-name=false) |
[nio-8080-exec-3] | Thread name |
c.j.shop.order.OrderService | Logger name, usually the class, with packages shortened |
Text after : | The message |
When tracing is enabled through Micrometer Tracing, a correlation section with the trace and span IDs is added automatically. You can change the patterns with logging.pattern.console and logging.pattern.file, but for machine processing JSON is the better choice.
5. Logging to a File with Rotation
By default Spring Boot logs only to the console, which is what containers and Kubernetes expect. To also write a file, set one property:
logging.file.name=logs/shop.log
logging.logback.rollingpolicy.max-file-size=20MB
logging.logback.rollingpolicy.max-history=14
logging.logback.rollingpolicy.total-size-cap=1GB
| Property | Default | Meaning |
|---|---|---|
logging.file.name | none | Log file path; wins over logging.file.path |
logging.file.path | none | Directory for a file named spring.log |
logging.logback.rollingpolicy.max-file-size | 10MB | Size at which the file is archived |
logging.logback.rollingpolicy.max-history | 7 | Number of archived files to keep |
logging.logback.rollingpolicy.total-size-cap | no limit | Maximum total size of the archives |
6. Structured JSON Logging
Structured logging writes each event as a JSON object instead of a line of text. Log platforms can then search by field (level, logger, order ID) without fragile text parsing. Spring Boot supports three formats out of the box: Elastic Common Schema (ecs), Graylog Extended Log Format (gelf) and Logstash (logstash).
logging.structured.format.console=ecs
{
"@timestamp": "2026-12-04T04:45:42.318Z",
"log": { "level": "INFO", "logger": "com.javabytechie.shop.order.OrderService" },
"process": { "pid": 48213, "thread": { "name": "http-nio-8080-exec-3" } },
"service": { "name": "shop" },
"message": "Order ORD-1001 placed",
"orderId": "ORD-1001",
"correlationId": "c0a8-7f3e",
"ecs": { "version": "8.11" }
}
Values in the MDC and key-value pairs from the fluent API become fields of the JSON object. The exact set of fields depends on the format and version, so check your output once before building dashboards. You can shape the JSON with properties:
logging.structured.json.exclude=ecs.version
logging.structured.json.add.environment=production
logging.structured.ecs.service.version=1.4.0
Use logging.structured.format.file for JSON files. A common setup is readable text in development and JSON in production, chosen per profile.
7. Correlation IDs with MDC
When many requests run at once, their log lines interleave. A correlation ID is a value added to every line of one request so you can filter them. SLF4J's MDC (Mapped Diagnostic Context) holds such values for the current thread, and the backend adds them to each log event.
A servlet filter is the right place to set it, because it runs once at the start of each request and can clean up at the end. The filter mechanics are explained in filters vs interceptors.
package com.javabytechie.shop.web;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;
import org.slf4j.MDC;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorrelationIdFilter extends OncePerRequestFilter {
static final String HEADER = "X-Correlation-Id";
static final String MDC_KEY = "correlationId";
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
String incoming = request.getHeader(HEADER);
String correlationId = (incoming != null && incoming.matches("[A-Za-z0-9-]{1,64}"))
? incoming
: UUID.randomUUID().toString();
MDC.put(MDC_KEY, correlationId);
response.setHeader(HEADER, correlationId);
try {
chain.doFilter(request, response);
} finally {
MDC.remove(MDC_KEY); // threads are reused; never leave values behind
}
}
}
To show the value in plain-text logs, add it to the pattern; JSON formats include MDC values automatically:
logging.pattern.correlation=[%X{correlationId:-}]
The incoming header is validated before use so a client cannot inject arbitrary text into your logs. If you use Micrometer Tracing, trace and span IDs are put into the MDC for you and propagated between services; see distributed tracing.
8. A Complete Example: Logging an Order Service
8.1 The Service
package com.javabytechie.shop.order;
import java.math.BigDecimal;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
@Service
public class OrderService {
private static final Logger log = LoggerFactory.getLogger(OrderService.class);
public String place(String customerId, List<String> skus, BigDecimal total) {
log.debug("Placing order for customer {} with items {}", customerId, skus);
if (skus.isEmpty()) {
log.warn("Rejected empty order from customer {}", customerId);
throw new IllegalArgumentException("An order needs at least one item");
}
String orderId = "ORD-" + (1000 + Math.abs(customerId.hashCode() % 9000));
log.atInfo()
.setMessage("Order placed")
.addKeyValue("orderId", orderId)
.addKeyValue("itemCount", skus.size())
.addKeyValue("total", total)
.log();
return orderId;
}
}
8.2 The Controller
package com.javabytechie.shop.order;
import java.math.BigDecimal;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/orders")
public class OrderController {
private final OrderService orders;
public OrderController(OrderService orders) {
this.orders = orders;
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public OrderPlaced place(@RequestBody PlaceOrder request) {
return new OrderPlaced(orders.place(request.customerId(), request.skus(), request.total()));
}
public record PlaceOrder(String customerId, List<String> skus, BigDecimal total) {
}
public record OrderPlaced(String orderId) {
}
}
8.3 Configuration per Profile
spring.application.name=shop
logging.level.com.javabytechie.shop=INFO
logging.pattern.correlation=[%X{correlationId:-}]
logging.level.com.javabytechie.shop=DEBUG
logging.structured.format.console=ecs
8.4 Output in Development
curl -s -X POST localhost:8080/api/orders -H "Content-Type: application/json" \
-H "X-Correlation-Id: checkout-42" \
-d '{"customerId":"CUST-7","skus":["KB-100","MS-200"],"total":104.98}'
2026-12-04T10:15:42.301+05:30 DEBUG 48213 --- [shop] [nio-8080-exec-3] [checkout-42] c.j.shop.order.OrderService : Placing order for customer CUST-7 with items [KB-100, MS-200]
2026-12-04T10:15:42.318+05:30 INFO 48213 --- [shop] [nio-8080-exec-3] [checkout-42] c.j.shop.order.OrderService : Order placed
In the text format the key-value pairs of the fluent call are not shown, but in the prod profile's JSON output they appear as orderId, itemCount and total fields, next to correlationId. The ID received in the header is reused, so the same request can be followed across services. Column widths are shortened here.
9. Changing Log Levels at Runtime
With Actuator, the loggers endpoint shows and changes levels while the application runs, which is ideal for switching on DEBUG briefly in production:
management.endpoints.web.exposure.include=health,loggers
curl -s localhost:8080/actuator/loggers/com.javabytechie.shop.order
curl -s -X POST localhost:8080/actuator/loggers/com.javabytechie.shop.order \
-H "Content-Type: application/json" -d '{"configuredLevel":"DEBUG"}'
# reset to the configured default
curl -s -X POST localhost:8080/actuator/loggers/com.javabytechie.shop.order \
-H "Content-Type: application/json" -d '{"configuredLevel":null}'
The change applies only to that instance and is lost on restart. Protect the endpoint with Spring Security; see Spring Boot Actuator.
10. Custom Logback Configuration and Log4j2
10.1 logback-spring.xml
When properties are not enough, for example to send one logger to a separate file, add logback-spring.xml to src/main/resources. Use the -spring name rather than logback.xml: Spring Boot then controls initialization and adds extensions such as <springProfile>.
<configuration>
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<include resource="org/springframework/boot/logging/logback/console-appender.xml"/>
<springProfile name="dev">
<logger name="com.javabytechie.shop" level="DEBUG"/>
</springProfile>
<root level="INFO">
<appender-ref ref="CONSOLE"/>
</root>
</configuration>
Including Spring Boot's defaults.xml and console-appender.xml keeps the standard patterns and colors. Once you provide this file, the file-related logging.* properties only work if your configuration includes the matching Spring Boot appenders.
10.2 Switching to Log4j2
Exclude the default logging starter and add the Log4j2 one. Your code does not change, because it uses the SLF4J API:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc</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>
11. Common Logging Mistakes
- String concatenation:
log.debug("Order " + order)builds the string even when DEBUG is off. Use{}placeholders. - Logging and rethrowing at every layer: the same stack trace appears five times. Log an exception once, where it is handled.
- Losing the stack trace:
log.error("Failed: " + ex.getMessage())drops the cause. Pass the exception as the last argument. - Logging secrets and personal data: tokens, passwords, card numbers and full request bodies do not belong in logs; see managing secrets.
- Leaving MDC values behind: without
MDC.removein afinallyblock, the next request on the same thread inherits the old value. System.out.println: it bypasses levels, formats and the log pipeline entirely.
12. Best Practices
- Log to the console in containers and let the platform collect and ship the output.
- Use JSON structured logging in production and readable text in development.
- Keep production at INFO and raise levels temporarily through the
loggersendpoint. - Add a correlation ID to every request with a filter and MDC, or with Micrometer Tracing.
- Log business events at INFO with stable keys such as
orderId, so they can be searched and counted. - Log each exception once, with its stack trace, at the place it is handled.
- Cap file growth with rotation properties whenever you write log files.
13. Summary
Logging in Spring Boot combines the SLF4J API with Logback, configured from logging.* properties. Set levels per package or with log groups, write rotating files with logging.file.name when you need them, and switch to JSON with logging.structured.format.console so log platforms can search by field. Add a correlation ID through a filter and MDC, attach business data with SLF4J's fluent key-value API, and change levels at runtime with the Actuator loggers endpoint. Keep messages meaningful, log exceptions once, and never log secrets, and your logs will answer questions instead of creating them.
14. References
Logging in Spring Boot Interview Questions and Answers
Common interview questions on Logging in Spring Boot, from basic to scenario-based, with short answers you can explain in your own words.
Q. Which logging framework does Spring Boot use by default, and how do SLF4J and Logback relate?
Answer: SLF4J is the API your code calls; Logback is the backend that filters, formats and writes the events. Every starter includes spring-boot-starter-logging, which brings Logback and bridges for other logging APIs, so all libraries end up in one output. Because code depends only on SLF4J, the backend can be switched to Log4j2 without code changes.
Q. What are log groups in Spring Boot?
Answer: A log group is a named set of loggers defined with logging.group.<name>=pkg1,pkg2, whose level can then be set with one logging.level.<name> property. Spring Boot predefines web for Spring MVC related loggers and sql for JDBC and Hibernate SQL logging. Groups make it easy to change the level of a whole feature at once.
Q. Why use logback-spring.xml instead of logback.xml?
Answer: With the -spring variant, Spring Boot loads the configuration itself after its environment is ready, so you can use extensions such as <springProfile> and <springProperty>. A plain logback.xml is loaded by Logback too early, before Spring knows about profiles and properties. Including Spring Boot's base XML files keeps the default patterns.
Q. What is structured logging, and how do you enable it in Spring Boot?
Answer: It means writing each log event as a machine-readable object, usually JSON, instead of a text line. Set logging.structured.format.console (or .file) to ecs, gelf or logstash. MDC values and SLF4J key-value pairs become separate fields, and logging.structured.json.* properties can add, remove or rename members. Custom formats are possible with a StructuredLogFormatter.
Q. What is MDC, and why must values be removed in a finally block?
Answer: The Mapped Diagnostic Context is a per-thread map of values, such as a correlation or user ID, that the logging backend adds to every event logged on that thread. Server threads are reused across requests, so a value left behind would be attached to the next request's logs. Removing it in finally guarantees cleanup even when the request fails.
Q. Production shows an intermittent error and you need DEBUG logs from one package without restarting. What do you do?
Answer: Use the Actuator loggers endpoint: POST {"configuredLevel":"DEBUG"} to /actuator/loggers/<package> on the affected instances, collect logs while the problem occurs, then reset it with null. The endpoint must be exposed and secured beforehand. With several instances, change each one, or use a correlation ID to find the relevant lines quickly.