Logging
So your app is running and something goes wrong. Without logging, you're flying blind. Logging is like leaving breadcrumbs — it tells you what happened, when it happened, and sometimes why it happened.
Spring Boot comes with Logback pre-configured and ready to go. No setup needed. You just start logging and it works out of the box. That's the Spring Boot way.
Log Levels
Log levels are like volume knobs for your logs. ERROR is for critical problems that need immediate attention. WARN is for potential issues. INFO is for normal operations. DEBUG is for detailed troubleshooting. TRACE is for the nitty-gritty details.
You don't want to see every single database query in production (that's DEBUG level), but when something breaks, you'll wish you had them. The trick is finding the right balance.
@Service
public class OrderService {
private static final Logger log = LoggerFactory.getLogger(OrderService.class);
public Order createOrder(OrderRequest request) {
log.info("Creating order for customer: {}", request.getCustomerId());
try {
Order order = orderRepository.save(new Order(request));
log.info("Order created successfully with ID: {}", order.getId());
return order;
} catch (Exception e) {
log.error("Failed to create order for customer: {}", request.getCustomerId(), e);
throw e;
}
}
}
Custom Loggers
By default, Spring Boot uses the class name as the logger name. But sometimes you want more control — maybe you want to log a specific component separately so you can filter it easily.
You can create as many loggers as you want. Just make sure to use meaningful names so you can find your logs when you need them. Nobody wants to search through "ROOT" logger output at 3 AM.
@Component
public class PaymentProcessor {
private static final Logger paymentLog = LoggerFactory.getLogger("PAYMENTS");
private static final Logger auditLog = LoggerFactory.getLogger("AUDIT");
public void processPayment(Payment payment) {
paymentLog.info("Processing payment: {}", payment.getId());
auditLog.info("User {} initiated payment of {}",
payment.getUserId(), payment.getAmount());
}
}
Logging Configuration
You can tweak logging behavior in application.properties. Want to change the log level for a specific package? Set logging.level.{package}={level}. Want to write logs to a file instead of the console? Set logging.file.name.
The logging configuration is your control panel. It lets you fine-tune what you see and where it goes, without touching a single line of code.
logging.level.root=WARN
logging.level.com.myapp=INFO
logging.level.com.myapp.database=DEBUG
logging.file.name=logs/myapp.log
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n