Video in progress

Junior 🌱 Spring

How do you write logs in Spring Boot, and how do you change the log level?

In code you use an SLF4J Logger, with Logback underneath by default. You change the level with a setting like logging.level.<package>=DEBUG.

📖 Answer

@Service
public class OrderService {
    private static final Logger log = LoggerFactory.getLogger(OrderService.class);

    public void pay(long orderId) {
        log.info("Paying order {}", orderId);      // {} is a parameter, not string concatenation
        try { ... }
        catch (PaymentException e) {
            log.error("Payment failed for order {}", orderId, e); // the last argument is the exception
        }
    }
}

Levels: TRACE < DEBUG < INFO < WARN < ERROR. Configuring them:

logging:
  level:
    root: INFO
    uz.shop.payment: DEBUG
    org.hibernate.SQL: DEBUG   # see the SQL Hibernate sends

A few habits:

  • write {}, not "Order " + id — if the level is off, the string isn't built at all;
  • never log passwords, card numbers or tokens;
  • pass the whole exception object, not e.getMessage() — otherwise the stack trace is lost.