Logging with SLF4J: levels and what to log
45 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)At 2 am an order fails and nobody is awake. The log is the only record of what happened, so every line needs a time, a level and the ids that make it searchable.
SLF4J and Logback: getting a Logger
SLF4J (Simple Logging Facade for Java) is the logging API your code calls, through org.slf4j.Logger. Logback is the library behind it in Spring Boot that formats and writes the lines.
Each class gets its own logger: private static final Logger log = LoggerFactory.getLogger(OrderService.class);. The class name becomes the logger name, shown in every line, so you know which class wrote it.
Example 1 · OrderService.java with an SLF4J Logger
Runs in: the config-lab practice project (Spring Boot 4.1)
// src/main/java/com/shoplite/lab/order/OrderService.javapackage com.shoplite.lab.order;
import java.math.BigDecimal;import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Service;
@Servicepublic class OrderService {
private static final Logger log = LoggerFactory.getLogger(OrderService.class);
private final AtomicInteger nextOrderId = new AtomicInteger(17);
public int placeOrder(int customerId, int items, BigDecimal total) { int orderId = nextOrderId.getAndIncrement(); log.info("Order {} placed by customer {}: {} item(s), total Rs {}", orderId, customerId, items, total); return orderId; }}
// src/main/java/com/shoplite/lab/order/OrderDemoRunner.javapackage com.shoplite.lab.order;
import java.math.BigDecimal;
import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
@Componentpublic class OrderDemoRunner implements CommandLineRunner {
private final OrderService orders;
public OrderDemoRunner(OrderService orders) { this.orders = orders; }
@Override public void run(String... args) { orders.placeOrder(5, 2, new BigDecimal("2796.00")); orders.placeOrder(2, 1, new BigDecimal("17999.00")); }}
# src/main/resources/application.propertiesspring.application.name=config-labspring.main.banner-mode=off2026-10-16T12:15:03.477+05:30 INFO 23808 --- [config-lab] [ main] com.shoplite.lab.ConfigLabApplication : No active profile set, falling back to 1 default profile: "default" 2026-10-16T12:15:05.222+05:30 INFO 23808 --- [config-lab] [ main] com.shoplite.lab.ConfigLabApplication : Started ConfigLabApplication in 2.831 seconds (process running for 3.837) 2026-10-16T12:15:05.233+05:30 INFO 23808 --- [config-lab] [ main] com.shoplite.lab.order.OrderService : Order 17 placed by customer 5: 2 item(s), total Rs 2796.00 2026-10-16T12:15:05.235+05:30 INFO 23808 --- [config-lab] [ main] com.shoplite.lab.order.OrderService : Order 18 placed by customer 2: 1 item(s), total Rs 17999.00
What this code does
- The logger is
static final: one per class, shared by every call. Its namecom.shoplite.lab.order.OrderServiceappears in each line. - The four
{}are filled from the four arguments in order.[config-lab]comes fromspring.application.nameand[main]is the thread. - The order counter is an
AtomicIntegerbecause the service is a singleton bean that many requests may use at once.
Every Spring Boot starter already brings both libraries, so there is nothing to add to pom.xml. Why not System.out.println? A println has no time, no level and no class name, cannot be switched off per package, and cannot be sent to a file or a log server. Real ShopLite code never prints; it logs.
A Boot log line is built like this:
- time with offset, level, process id,
[app name],[thread], a shortened logger name, then:and your message - long package names are shortened from the left (
c.shoplite.lab.delivery.DeliveryService) to fit 40 characters
Levels TRACE to ERROR and logging.level per package
A log level says how serious a line is: TRACE, DEBUG, INFO, WARN or ERROR, from most detail to most serious. A logger prints a line only when its level is at or above the configured level.
The levels run from TRACE (most detail) to ERROR (most serious). Boot's default is INFO, so TRACE and DEBUG lines are skipped. logging.level.<package>=<level> changes that for one package.
Example 2 · DeliveryService.java: one line at every level
Runs in: the config-lab practice project (Spring Boot 4.1)
// src/main/java/com/shoplite/lab/delivery/DeliveryService.javapackage com.shoplite.lab.delivery;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Service;
@Servicepublic class DeliveryService {
private static final Logger log = LoggerFactory.getLogger(DeliveryService.class);
public void ship(int orderId, String pincode) { log.trace("ship() called with orderId={}, pincode={}", orderId, pincode); log.debug("Looking up courier for PIN code {}", pincode); log.info("Order {} handed to the courier", orderId); log.warn("Courier for {} is 2 days behind; order {} may be late", pincode, orderId); log.error("Courier API refused order {}; will retry in 5 minutes", orderId); }}
# src/main/resources/application.propertiesspring.application.name=config-labspring.main.banner-mode=offlogging.level.root=warnlogging.level.com.shoplite=info$ java -jar target/config-lab-0.0.1-SNAPSHOT.jar 2026-10-16T12:15:22.731+05:30 INFO 8736 --- [config-lab] [ main] c.shoplite.lab.delivery.DeliveryService : Order 14 handed to the courier 2026-10-16T12:15:22.731+05:30 WARN 8736 --- [config-lab] [ main] c.shoplite.lab.delivery.DeliveryService : Courier for 600017 is 2 days behind; order 14 may be late 2026-10-16T12:15:22.732+05:30 ERROR 8736 --- [config-lab] [ main] c.shoplite.lab.delivery.DeliveryService : Courier API refused order 14; will retry in 5 minutes $ java -jar target/config-lab-0.0.1-SNAPSHOT.jar --logging.level.com.shoplite.lab.delivery=debug 2026-10-16T12:15:17.013+05:30 DEBUG 29952 --- [config-lab] [ main] c.shoplite.lab.delivery.DeliveryService : Looking up courier for PIN code 600017 2026-10-16T12:15:17.017+05:30 INFO 29952 --- [config-lab] [ main] c.shoplite.lab.delivery.DeliveryService : Order 14 handed to the courier 2026-10-16T12:15:17.017+05:30 WARN 29952 --- [config-lab] [ main] c.shoplite.lab.delivery.DeliveryService : Courier for 600017 is 2 days behind; order 14 may be late 2026-10-16T12:15:17.017+05:30 ERROR 29952 --- [config-lab] [ main] c.shoplite.lab.delivery.DeliveryService : Courier API refused order 14; will retry in 5 minutes $ java -jar target/config-lab-0.0.1-SNAPSHOT.jar --logging.level.com.shoplite=error 2026-10-16T12:15:28.894+05:30 ERROR 27460 --- [config-lab] [ main] c.shoplite.lab.delivery.DeliveryService : Courier API refused order 14; will retry in 5 minutes
What this code does
- At INFO, the TRACE and DEBUG lines are skipped. Setting the
deliverypackage to DEBUG adds the DEBUG line; TRACE needs=trace. - Setting
com.shopliteto ERROR hides everything below ERROR in all ShopLite packages, becausedeliverysits insidecom.shoplite. - A small runner calls
ship(14, "600017"); the start-up lines are left out of the output.
INFO is for normal business events (order placed), WARN for something unusual that the app handled (courier late), ERROR for something that failed and needs a person, DEBUG for details for developers and TRACE for every step. The level set for a package covers everything below it: logging.level.com.shoplite=debug. The most specific package wins, and logging.level.root covers everything else, including Spring's own logs.
Because these are normal settings, you can raise a level on a live server for a few minutes with an argument or environment variable (LOGGING_LEVEL_COM_SHOPLITE=debug) without a new build.
Predict the output
Which lines are printed?
Read the settings and the calls, then pick the result.
Round 1 of 3
Which of the three lines appear in the log?
Messages with {} and logging an exception
A parameterised message is a log message with {} for each value, such as log.info("Order {} placed", orderId). The values are filled in only when the line is really written.
Write each value as {}: log.info("Order {} placed by customer {}", orderId, customerId). To log an exception, pass it as the last argument: log.error("Payment failed for order {}", orderId, e).
Example 3 · PaymentService.java: losing and keeping the stack trace
Runs in: the config-lab practice project (Spring Boot 4.1)
package com.shoplite.lab.payment;
import java.math.BigDecimal;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Service;
@Servicepublic class PaymentService {
private static final Logger log = LoggerFactory.getLogger(PaymentService.class);
public boolean collect(int orderId, BigDecimal amount) { try { callUpiGateway(orderId, amount); return true; } catch (IllegalStateException e) { // Wrong: string joining, and only the message, so the stack trace is lost log.error("Payment failed for order " + orderId + ": " + e.getMessage());
// Right: {} placeholders, and the exception as the LAST argument log.error("Payment failed for order {} (Rs {})", orderId, amount, e); return false; } }
private void callUpiGateway(int orderId, BigDecimal amount) { throw new IllegalStateException("UPI gateway timed out after 10 s"); }}
package com.shoplite.lab.payment;
import java.math.BigDecimal;
import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
@Componentpublic class PaymentRunner implements CommandLineRunner {
private final PaymentService payments;
public PaymentRunner(PaymentService payments) { this.payments = payments; }
@Override public void run(String... args) { boolean paid = payments.collect(17, new BigDecimal("2796.00")); System.out.println("Paid? " + paid); }}2026-10-16T12:15:39.421+05:30 ERROR 23580 --- [config-lab] [ main] c.shoplite.lab.payment.PaymentService : Payment failed for order 17: UPI gateway timed out after 10 s 2026-10-16T12:15:39.438+05:30 ERROR 23580 --- [config-lab] [ main] c.shoplite.lab.payment.PaymentService : Payment failed for order 17 (Rs 2796.00) java.lang.IllegalStateException: UPI gateway timed out after 10 s at com.shoplite.lab.payment.PaymentService.callUpiGateway(PaymentService.java:29) ~[classes/:na] at com.shoplite.lab.payment.PaymentService.collect(PaymentService.java:16) ~[classes/:na] at com.shoplite.lab.payment.PaymentRunner.run(PaymentRunner.java:19) ~[classes/:na] ... (about 20 more "at" lines from Spring Boot and the JDK) Paid? false
What this code does
- The first line shows only the message: there is no clue which class and line failed. Both calls are in one method here only to compare them; real code logs once.
- The second call passes
eafter the two{}values, so Logback prints the exception class, message and everyatline. The top line,PaymentService.java:29, is where it was thrown. - The method still returns
false, so the caller can show "Payment failed, please try again" instead of crashing.
The values are filled in only if the line is really written, which is cheaper than joining strings with + and keeps the message text the same for every order, so it is easy to search for. SLF4J notices that the last argument is a Throwable, does not use it for a {}, and prints the full stack trace below the message.
The common mistake is log.error("... " + e.getMessage()). You get one line and lose the stack trace, which is the part that says where the failure happened. Log each exception once, where you handle it; logging and rethrowing at every layer prints the same trace many times.
Fix the error
Fix the log call
Each log line hides something. Pick the line that replaces the marked one.
Round 1 of 2
The log shows the message but no stack trace.
Error
ERROR PaymentService : Payment failed: Connection refused (no stack trace, no order id)
What to log, and what never to log
Masking means hiding most of a personal value before it is logged, such as ******3205 for a phone number, while keeping enough to identify it.
Log business events with ids and numbers, and never log secrets or personal data. Example 4 shows small masking helpers for a phone number and a card.
Example 4 · Masking personal data before it reaches a log
final class Mask {
private Mask() { }
/** 9876543205 -> ******3205 */ static String phone(String phone) { if (phone == null || phone.length() < 4) { return "****"; } return "*".repeat(phone.length() - 4) + phone.substring(phone.length() - 4); }
/** 4111 1111 1111 1234 -> card ending 1234 */ static String card(String cardNumber) { String digits = cardNumber.replaceAll("[^0-9]", ""); return "card ending " + digits.substring(digits.length() - 4); }
/** priya.sharma@example.com -> p***@example.com */ static String email(String email) { int at = email.indexOf('@'); if (at < 1) { return "***"; } return email.charAt(0) + "***" + email.substring(at); }}
public class MaskingDemo {
public static void main(String[] args) { String phone = "9876543205"; String card = "4111 1111 1111 1234"; String email = "priya.sharma@example.com"; String password = "Shop#Lite2026";
System.out.println("NEVER: Login failed for " + email + " with password " + password); System.out.println("NEVER: Paid with card " + card + ", OTP sent to " + phone); System.out.println(); System.out.println("OK: Login failed for " + Mask.email(email) + " (wrong password)"); System.out.println("OK: Paid with " + Mask.card(card) + ", OTP sent to " + Mask.phone(phone)); System.out.println("OK: Order 17 placed by customer 5, total Rs 2796.00, took 42 ms"); }}NEVER: Login failed for priya.sharma@example.com with password Shop#Lite2026 NEVER: Paid with card 4111 1111 1111 1234, OTP sent to 9876543205 OK: Login failed for p***@example.com (wrong password) OK: Paid with card ending 1234, OTP sent to ******3205 OK: Order 17 placed by customer 5, total Rs 2796.00, took 42 ms
What this code does
- The NEVER lines show what must not appear in any log: a password, a full card number and a full phone number.
- The masked lines keep enough to help support staff (which customer, which card, which phone) without exposing the data. In a service you would pass the masked values to
log.info(...). - This is plain Java and runs without Spring; the helpers can live in a small utility class in
com.shoplite.common.
Log events such as order placed (order id, customer id, total), stock changed (product id, old and new stock) and a slow operation with its time in milliseconds. Someone reading the log must be able to answer "what happened to order 17?" without the database.
Never log passwords, OTPs, tokens and API keys, full card numbers, CVV, full phone numbers, Aadhaar or PAN numbers. Logs are copied to many systems and read by many people; anything in a log has leaked. India's Digital Personal Data Protection Act also expects companies to protect customers' personal data. When a value helps but is personal, mask it: the last four digits of a card or phone, the first letter of an email.
Log files, patterns and structured JSON logs
A structured log writes each line as one JSON object with named fields, such as log.level and message, so log tools can filter it without parsing text.
logging.file.name=logs/shoplite.log also writes every line to a file, and logging.structured.format.console=ecs prints one JSON object per line. Example 5 uses a file in dev and JSON in prod.
Example 5 · A log file in dev and JSON lines in prod
Runs in: the config-lab practice project (Spring Boot 4.1)
# src/main/resources/application.propertiesspring.application.name=shoplite-apispring.main.banner-mode=offlogging.level.root=warnlogging.level.com.shoplite=info# src/main/resources/application-dev.propertieslogging.level.com.shoplite=debuglogging.file.name=logs/shoplite-dev.log# src/main/resources/application-prod.propertieslogging.structured.format.console=ecs$ java -jar target/config-lab-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev
2026-10-16T12:17:51.325+05:30 INFO 27980 --- [shoplite-api] [ main] com.shoplite.lab.order.OrderService : Order 17 placed by customer 5: 2 item(s), total Rs 2796.00
2026-10-16T12:17:51.326+05:30 INFO 27980 --- [shoplite-api] [ main] com.shoplite.lab.order.OrderService : Order 18 placed by customer 2: 1 item(s), total Rs 17999.00
$ tail -1 logs/shoplite-dev.log
2026-10-16T12:17:51.326+05:30 INFO 27980 --- [shoplite-api] [main] com.shoplite.lab.order.OrderService : Order 18 placed by customer 2: 1 item(s), total Rs 17999.00
$ java -jar target/config-lab-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod
{"@timestamp":"2026-10-16T06:48:00.398229700Z","log":{"level":"INFO","logger":"com.shoplite.lab.order.OrderService"},"process":{"pid":25312,"thread":{"name":"main"}},"service":{"name":"shoplite-api","node":{}},"message":"Order 17 placed by customer 5: 2 item(s), total Rs 2796.00","ecs":{"version":"8.11"}}
{"@timestamp":"2026-10-16T06:48:00.401746500Z","log":{"level":"INFO","logger":"com.shoplite.lab.order.OrderService"},"process":{"pid":25312,"thread":{"name":"main"}},"service":{"name":"shoplite-api","node":{}},"message":"Order 18 placed by customer 2: 1 item(s), total Rs 17999.00","ecs":{"version":"8.11"}}What this code does
- The code is
OrderServicefrom Example 1; only the profile changes. Indevthe lines go to the console and tologs/shoplite-dev.log(the file layout has no padding around the thread name). - In
prodevery line is one JSON object:@timestampin UTC,log.level,log.logger,messageand the service name. A log tool can filter onlog.level= WARN without parsing text. - Add
logs/to.gitignore: log files never belong in Git.
Boot starts a new file when it reaches 10 MB and keeps 7 days of old files by default. logging.pattern.console replaces the line layout with your own Logback pattern, for example %d{HH:mm:ss} %-5level %logger{20} - %msg%n. On a server, logs are usually collected by a tool such as the ELK stack, Grafana Loki or a cloud log service, and those read JSON lines best. Spring Boot (3.4 and later, including 4.1) writes them with that one setting; other formats are logstash and gelf.
Put these choices in profile files: readable lines and DEBUG for dev, JSON and INFO for prod, so the code never changes between environments.
Next step
Check your understanding
11 quick questions