Careeroza
Log Levels
The Five Levels
| Level | Use for | ShopEase example |
|---|---|---|
ERROR | something failed and needs attention | payment gateway call failed |
WARN | unexpected but handled | stock is low, retrying a call |
INFO | important business events (default level) | order 101 placed |
DEBUG | details for developers | computed cart total and discounts |
TRACE | very detailed, step by step | every field of a request |
A logger prints a message only if its level is equal to or more severe than the configured level. With level INFO: ERROR, WARN and INFO are printed; DEBUG and TRACE are not.
Level Filtering
Example
An enum models the order of severity. Changing the configured level changes what gets printed:
import java.util.List;
public class Main {
enum Level { TRACE, DEBUG, INFO, WARN, ERROR }
record LogEvent(Level level, String message) {}
public static void main(String[] args) {
List<LogEvent> events = List.of(
new LogEvent(Level.TRACE, "Request headers: {Accept=application/json}"),
new LogEvent(Level.DEBUG, "Cart total computed: 2998"),
new LogEvent(Level.INFO, "Order 101 placed"),
new LogEvent(Level.WARN, "Stock for product 1 is low: 3 left"),
new LogEvent(Level.ERROR, "Payment failed for order 102: gateway timeout"));
for (Level configured : List.of(Level.INFO, Level.DEBUG, Level.ERROR)) {
System.out.println("--- logging.level = " + configured + " ---");
for (LogEvent e : events) {
if (e.level().compareTo(configured) >= 0) {
System.out.printf("%-5s %s%n", e.level(), e.message());
}
}
}
}
}Output
--- logging.level = INFO --- INFO Order 101 placed WARN Stock for product 1 is low: 3 left ERROR Payment failed for order 102: gateway timeout --- logging.level = DEBUG --- DEBUG Cart total computed: 2998 INFO Order 101 placed WARN Stock for product 1 is low: 3 left ERROR Payment failed for order 102: gateway timeout --- logging.level = ERROR --- ERROR Payment failed for order 102: gateway timeout
Logging Exceptions
try {
paymentGateway.charge(orderId, amount);
} catch (PaymentException e) {
// pass the exception as the LAST argument: the full stack trace is logged
log.error("Payment failed for order {}", orderId, e);
throw e;
}Note: Never log passwords, full card numbers, OTPs or tokens. Logs are read by many people and kept for a long time; leaking personal data in logs can break laws such as India's DPDP Act.