Logging is more than just writing messages to a console — it’s the heartbeat of every well-monitored application. Whether you’re debugging an issue, tracing a request, or tracking usage patterns, logging provides the insights developers need to understand what’s happening under the hood.
In this blog, we’ll explore logging in Spring Boot by walking through a hands-on example. We’ll cover:
- • Why logging matters
- • Logging levels and best practices
- • Logging configuration in application.properties
- • Writing clean, contextual logs
- • Example: A simple user management API with detailed logging
Why is Logging Important?
Imagine your application crashes in production. How do you know what went wrong? You can’t debug production code live, but with proper logging, you can replay the story of what happened.
Key benefits of good logging:
- • Troubleshooting: Identify and resolve bugs faster.
- • Audit Trail: Track what users or services are doing.
- • Performance Monitoring: Spot slowdowns or unusual behaviour.
- • Security Analysis: Detects suspicious activities.
Understanding Log Levels in Spring Boot
Spring Boot uses SLF4J with Logback under the hood. Each log message falls under a level:
| Level | Purpose | When to Use |
| TRACE | Very detailed logs, often used for debugging flow | Rarely used in production |
| DEBUG | Useful info for debugging | During development or testing |
| INFO | General application progress | For major lifecycle events |
| WARN | Potential issues | When something might go wrong |
| ERROR | Serious problems | When the app can’t proceed correctly |
Configuring Logging in Spring Boot
We can control the verbosity and formatting of logs via application.properties.
# Set logging levels
logging.level.root=INFO
logging.level.com.example.loggingpoc=DEBUG# Customize console format
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
# Enable request/response logging for Spring Web
logging.level.org.springframework.web=DEBUG
This setup ensures that:
- • Logs from your application (com.example.loggingpoc) include DEBUG-level detail
- • Spring framework logs basic HTTP request info
- • Console logs are easy to read
Boost Your Tech Team with Developers Who Deliver Quality and Speed
Real-World Example: Logging in a User Management API
Let’s dive into a practical example to see how logging works in a real Spring Boot app.
UserDTO: Our Data Model
public class UserDTO {
private String id;
private String name;
private String email;
// Constructors, getters, and setters...
}This DTO (Data Transfer Object) holds user data that travels between the controller and service layers.
UserService: Business Logic with Logging
Here’s how we simulate creating and fetching users — and log all key events and errors:
@Service
public class UserService {
private static final Logger log = LoggerFactory.getLogger(UserService.class);
public UserDTO getUser(String id) {
log.info("Fetching user with id: {}", id);
try {
Thread.sleep(100); // simulate processing
} catch (InterruptedException e) {
log.error("Interrupted while processing", e);
Thread.currentThread().interrupt();
}
UserDTO user = new UserDTO(id, "John Doe", "john@example.com");
log.debug("User details: {}", user);
return user;
}
public UserDTO createUser(UserDTO userDTO) {
log.info("Creating new user: {}", userDTO.getName());
if (userDTO.getEmail() == null || userDTO.getEmail().isEmpty()) {
log.warn("User creation attempted with empty email");
throw new IllegalArgumentException("Email cannot be empty");
}
log.debug("User created successfully: {}", userDTO);
return userDTO;
}
}What’s Happening Here?
- • We log at INFO when an operation begins.
- • We use DEBUG to log internal data (like returned user objects).
- • We catch exceptions and log at ERROR, never letting stack traces disappear silently.
UserController: Logging at the Web Layer
@RestController
@RequestMapping("/api/users")
public class UserController {
private static final Logger log = LoggerFactory.getLogger(UserController.class);
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping("/{id}")
public ResponseEntity<UserDTO> getUser(@PathVariable String id) {
log.info("Received request to get user with id: {}", id);
UserDTO user = userService.getUser(id);
log.debug("Returning user: {}", user);
return ResponseEntity.ok(user);
}
@PostMapping
public ResponseEntity<UserDTO> createUser(@RequestBody UserDTO userDTO) {
log.info("Received request to create user: {}", userDTO.getName());
try {
UserDTO createdUser = userService.createUser(userDTO);
log.debug("User created successfully: {}", createdUser);
return ResponseEntity.ok(createdUser);
} catch (IllegalArgumentException e) {
log.error("Error creating user: {}", e.getMessage());
return ResponseEntity.badRequest().build();
}
}This controller exposes two endpoints:
- • GET /api/users/{id}: Fetches a user
- • POST /api/users: Creates a new user
Each endpoint logs:
- • Input data (userDTO, id)
- • Outcome (createdUser, error messages)
Sample Log Output
Here’s what the logs look like when the API runs:
2025-06-02 10:00:00 [http-nio-8080-exec-1] INFO UserController - Received request to get user with id: 123
2025-06-02 10:00:00 [http-nio-8080-exec-1] INFO UserService - Fetching user with id: 123
2025-06-02 10:00:00 [http-nio-8080-exec-1] DEBUG UserService - User details: UserDTO{id='123', name='John Doe', email='john@example.com'}
2025-06-02 10:00:00 [http-nio-8080-exec-1] DEBUG UserController - Returning user: UserDTO{id='123', name='John Doe', email='john@example.com'}And here’s an error scenario:
2025-06-02 10:01:00 [http-nio-8080-exec-3] INFO UserController - Received request to create user: Alice
2025-06-02 10:01:00 [http-nio-8080-exec-3] INFO UserService - Creating new user: Alice
2025-06-02 10:01:00 [http-nio-8080-exec-3] WARN UserService - User creation attempted with empty email
2025-06-02 10:01:00 [http-nio-8080-exec-3] ERROR UserController - Error creating user: Email cannot be emptyThese logs are invaluable when debugging production issues or tracking down bugs during development.
Spring Boot 3.4 Logging
Spring Boot 3.4 introduces native support for structured logging, enabling logs to be emitted in machine-readable formats like JSON, adhering to schemas such as:
- • Elastic Common Schema (ECS)
- • Logstash
- • Graylog Extended Log Format (GELF)
This enhancement facilitates seamless integration with log aggregation tools like ELK Stack, Splunk, and Grafana, improving log analysis and monitoring capabilities.
Related read: 19 Point Checklist: Starting a New Project in Spring Boot
Benefits of Structured Logging
Structured logging offers several advantages:
- • Machine-Readable Logs: Logs are formatted as JSON objects, making them easily parsable by log management systems.
- • Enhanced Searchability: Key-value pairs allow for precise filtering and querying.
- • Improved Observability: Facilitates better monitoring and debugging in distributed systems.
- • Consistency: Adheres to standardized schemas, ensuring uniformity across services.
Configuring Structured Logging in Spring Boot 3.4
To enable structured logging:
1. Console Output: Add the following to your application.properties:
logging.structured.format.console=ecs
This configures the console to output logs in the ECS JSON format.
2. File Output: To write structured logs to a file:
logging.structured.format.file=ecs
logging.file.name=log.jsonThis setup writes human-readable logs to the console and structured logs to log.json.
3. Additional Metadata: Enrich logs with service-related metadata:
logging.structured.ecs.service.name=LoggingPOC
logging.structured.ecs.service.version=1.0.0
logging.structured.ecs.service.environment=Production
logging.structured.ecs.service.node-name=Node1These fields provide context, aiding in log analysis and correlation.
Implementing Structured Logging
1. Enriching Logs with Contextual Data
Utilize Mapped Diagnostic Context (MDC) to add contextual information:
import org.slf4j.MDC;
MDC.put("userId", "12345");
log.info("User login attempt");
MDC.clear();
import org.slf4j.MDC;
MDC.put("userId", "12345");
log.info("User login attempt");
MDC.clear();This approach appends the userId to the log entry, enhancing traceability.
Alternatively, use the fluent logging API:
log.atInfo()
.setMessage("User login attempt")
.addKeyValue("userId", "12345")
.log();This method provides a more concise way to add structured data to logs.
2. Sample Log OutputWith structured logging enabled, a log entry might look like:
{
"@timestamp": "2025-06-03T07:17:38.123Z",
"log.level": "INFO",
"process.thread.name": "main",
"service.name": "LoggingPOC",
"log.logger": "com.example.loggingpoc.controller.UserController",
"message": "User login attempt",
"userId": "12345",
"ecs.version": "8.11"
}This JSON structure allows for efficient parsing and analysis by log management tools.
Customizing Log Formats
Spring Boot 3.4 allows for custom structured log formats:
1. Implement StructuredLogFormatter:
public class CustomLogFormatter implements StructuredLogFormatter<ILoggingEvent>
{
@Override
public String format(ILoggingEvent event) {
return String.format("time=%d level=%s message=%s%n",
event.getTimeStamp(), event.getLevel(), event.getMessage());
}
}
2. Configure the Custom Formatter:
logging.structured.format.console=com.example.loggingpoc.logging.CustomLogFormatter
This configuration directs Spring Boot to use your custom formatter for console logs.
Integrating Structured Logging
1. Update application.properties:
# Server configuration
server.port=8080
# Logging configuration
logging.level.root=INFO
logging.level.com.example.loggingpoc=DEBUG
# Structured logging
logging.structured.format.console=ecs
logging.structured.ecs.service.name=LoggingPOC
logging.structured.ecs.service.version=1.0.0
logging.structured.ecs.service.environment=Development
logging.structured.ecs.service.node-name=Node12. Modify UserController to Include Contextual Data:
import org.slf4j.MDC;
@GetMapping("/{id}")
public ResponseEntity<UserDTO> getUser(@PathVariable String id) {
MDC.put("userId", id);
log.info("Received request to get user");
UserDTO user = userService.getUser(id);
log.debug("Returning user: {}", user);
MDC.clear();
return ResponseEntity.ok(user);
}This modification enriches the log entries with the userId, aiding in traceability.
Why Logging Matters (and What to Avoid)
Do:
- • Use info for important business milestones.
- • Use debug for insights into data transformation, inputs, outputs.
- • Log meaningful messages — “User created” is better than “Done.”
- • Include dynamic values using {} placeholders.
Don’t:
- • Log sensitive data like passwords.
- • Overuse debug in production unless needed.
- • Catch exceptions and ignore them silently.
Effective logging is a superpower. It gives you visibility, traceability, and control — especially in production systems where you can’t just “debug.”
With just a few thoughtful lines, you can:
- • Make your APIs self-explaining
- • Understand failures before users even report them
- • Reduce MTTR (Mean Time To Resolution)

Conclusion
By leveraging the structured logging capabilities introduced in Spring Boot 3.4, your application gains:
- • Enhanced log clarity and consistency.
- • Improved integration with log analysis tools.
- • Greater observability and debugging efficiency.
Implementing these features ensures your application is well-equipped for modern monitoring and analysis requirements.






























