Imagine a microservice zoo with dozens or even hundreds of independent services. What do you do if one of them suddenly stops behaving correctly? How do you figure out what broke, where, and why? That's where logging steps in. Logs are your footprints in the microservice desert.
Logging in microservices is especially important because:
- Each microservice has its own database, business logic, and configuration.
- Microservices talk to each other over the network, so you need to track requests and responses.
- Errors can happen in any service — you need data to quickly find the root cause.
Spring Boot makes logging setup easier thanks to integration with popular libraries like SLF4J and Logback.
Logging basics with SLF4J and Logback
SLF4J (Simple Logging Facade for Java) is a facade for different logging tools. It helps decouple your code from a concrete implementation (e.g., Logback, Log4j) and makes it easy to swap one library for another without changing application code.
In Spring Boot, Logback is used out of the box. You don't need to add extra dependencies — just provide configurations and use loggers correctly.
Creating a logger
Say we have CustomerService and want to log actions in that class:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
@Service
public class CustomerService {
private static final Logger logger = LoggerFactory.getLogger(CustomerService.class);
public void handleCustomerRequest(String customerId) {
logger.info("Handling request for customer: {}", customerId);
try {
// Processing logic
logger.debug("Processing customer data for ID: {}", customerId);
} catch (Exception e) {
logger.error("Error while processing customer data", e);
}
}
}
Log levels
Log levels let you set the importance of messages:
TRACE— the most detailed logging. Rarely used.DEBUG— for development, to see execution details.INFO— general runtime information.WARN— warnings about potential issues.ERROR— errors that lead to failures or incorrect behavior.
Configuring logging via application.yml
You can configure logging directly in application.yml using Spring Boot:
logging:
level:
root: INFO # General logging
com.example: DEBUG # Logging for a specific package
file:
name: logs/app.log # Output logs to a file
pattern:
console: "%d{yyyy-MM-dd HH:mm:ss} - %msg%n" # Pattern for console logs
Now all our DEBUG logs for package com.example will be shown in the console and written to logs/app.log.
Logging override order
- Settings at the
application.ymlorapplication.propertieslevel. - Configuration via the
logback.xmlfile (if you need more complex log formats). - Environment variables, if you need to temporarily change logging level in production.
Monitoring microservices
Logging alone is sometimes not enough. You should also watch the service's health, resource consumption, and other important metrics. For that, Spring Boot provides a powerful tool — Spring Boot Actuator.
What is Spring Boot Actuator?
Actuator is a set of built-in endpoints that provide information about the application. With it you can:
- Find out the status of external dependencies (e.g., the database).
- Get performance metrics (response time, memory usage, etc.).
- Check which endpoints are ready to interact.
Enabling Spring Boot Actuator
Add the dependency to pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Actuator automatically activates several endpoints. Let's configure them.
Configuring Actuator in application.yml
Let's enable basic metrics:
management:
endpoints:
web:
exposure:
include: "*" # Allow all endpoints
endpoint:
health:
show-details: always # Show detailed service health info
metrics:
enabled: true # Enable metrics
Now, after starting the app, we can access various Actuator endpoints (for example, /actuator/health).
Actuator endpoints
| Endpoint | Description |
|---|---|
/actuator/health |
Service health check |
/actuator/metrics| Performance metrics |
|
/actuator/env |
Information about environment variables |
/actuator/loggers| Dynamic log level management |
Example: let's check the server health
curl http://localhost:8080/actuator/health
Result:
{
"status": "UP"
}
Practical application: setting up logging and monitoring
1. Setting up logs for a microservice
Say we're building an order management service OrderService. We need to:
- Add logging to the main methods (create order, update, delete).
- Persist logs to a file so they can be shipped to a centralized logging system.
Example OrderService with logging:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
@Service
public class OrderService {
private static final Logger logger = LoggerFactory.getLogger(OrderService.class);
public void createOrder(String orderId) {
logger.info("Creating order with ID: {}", orderId);
}
public void updateOrder(String orderId) {
logger.debug("Updating order with ID: {}", orderId);
}
public void deleteOrder(String orderId) {
logger.warn("Deleting order with ID: {}", orderId);
}
}
Let's configure log output to a file via application.yml:
logging:
level:
root: INFO
com.example.orderservice: DEBUG
file:
name: logs/orderservice.log
2. Enabling metrics via Actuator
Let's add info about the service uptime via Actuator. Check it via /actuator/metrics.
Example call:
curl http://localhost:8080/actuator/metrics/jvm.uptime
Real problems and how to avoid them
- Too much noise in the logs? Use log levels (DEBUG only for development).
- Log files too big? Configure log rotation via
logback.xml. - Not enough metrics? Integrate Actuator with tools like Prometheus and Grafana for comprehensive monitoring.
For centralized logging in real projects, people often use the ELK stack (Elasticsearch, Logstash, Kibana). Spring Boot integrates with this stack easily.
Practice for students
- Add logging to all main services of your application:
- Use levels
INFO,DEBUG, andERROR. - Persist logs to a file and check its contents.
- Use levels
- Set up Actuator:
- Enable
/actuator/health. - Check availability of metrics via
/actuator/metrics.
- Enable
- (Optional) Integrate Actuator with Prometheus and visualize metrics in Grafana.
GO TO FULL VERSION