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:
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:
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 |
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:
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?
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:
Each endpoint logs:
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 empty
These logs are invaluable when debugging production issues or tracking down bugs during development.
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:
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
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.json
This 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=Node1
These fields provide context, aiding in log analysis and correlation.
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.
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.
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=Node1
2. 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.
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:
By leveraging the structured logging capabilities introduced in Spring Boot 3.4, your application gains:
Implementing these features ensures your application is well-equipped for modern monitoring and analysis requirements.
We worked with Mindbowser on a design sprint, and their team did an awesome job. They really helped us shape the look and feel of our web app and gave us a clean, thoughtful design that our build team could...
The team at Mindbowser was highly professional, patient, and collaborative throughout our engagement. They struck the right balance between offering guidance and taking direction, which made the development process smooth. Although our project wasn’t related to healthcare, we clearly benefited...
Founder, Texas Ranch Security
Mindbowser played a crucial role in helping us bring everything together into a unified, cohesive product. Their commitment to industry-standard coding practices made an enormous difference, allowing developers to seamlessly transition in and out of the project without any confusion....
CEO, MarketsAI
I'm thrilled to be partnering with Mindbowser on our journey with TravelRite. The collaboration has been exceptional, and I’m truly grateful for the dedication and expertise the team has brought to the development process. Their commitment to our mission is...
Founder & CEO, TravelRite
The Mindbowser team's professionalism consistently impressed me. Their commitment to quality shone through in every aspect of the project. They truly went the extra mile, ensuring they understood our needs perfectly and were always willing to invest the time to...
CTO, New Day Therapeutics
I collaborated with Mindbowser for several years on a complex SaaS platform project. They took over a partially completed project and successfully transformed it into a fully functional and robust platform. Throughout the entire process, the quality of their work...
President, E.B. Carlson
Mindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. I’m excited to...
Founder, Seeke
We had very close go live timeline and Mindbowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project.
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
Mindbowser was great; they listened to us a lot and helped us hone in on the actual idea of the app. They had put together fantastic wireframes for us.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork