What to log at each level
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite works on your laptop, but at 2 a.m. on a server the log is the only witness to what went wrong. A line at the wrong level either hides the problem or buries it.
Why System.out is not logging
A logger is an object that writes messages with a level, a time and the source, and sends them where the configuration says. Each logger is named after its class.
Here is one order handled twice: first with three System.out.println lines, then with three logger calls. Compare what each shows.
Example 1 · System.out vs a logger
import java.util.logging.Level;import java.util.logging.Logger;
public class PrintlnVsLoggerDemo { static { // only for this page: log lines on System.out, without the date line System.setErr(System.out); System.setProperty("java.util.logging.SimpleFormatter.format", "%4$-7s [%3$s] %5$s%n"); }
private static final Logger log = Logger.getLogger("com.shoplite.order.OrderService");
static void placeOrderWithPrintln(int customerId, int stockLeft) { System.out.println("placing order for customer " + customerId); System.out.println("stock low: " + stockLeft + " left"); System.out.println("order saved"); }
static void placeOrderWithLogger(int customerId, int stockLeft) { log.fine("Placing order for customer " + customerId); log.warning("Stock of MOB-IP15 is low: " + stockLeft + " left"); log.info("Order 17 placed by customer " + customerId); }
public static void main(String[] args) { System.out.println("--- System.out ---"); placeOrderWithPrintln(5, 2);
System.out.println("--- Logger, default level INFO ---"); placeOrderWithLogger(5, 2);
System.out.println("--- Logger set to WARNING: one line changes what you see ---"); log.setLevel(Level.WARNING); placeOrderWithLogger(5, 2); }}--- System.out --- placing order for customer 5 stock low: 2 left order saved --- Logger, default level INFO --- WARNING [com.shoplite.order.OrderService] Stock of MOB-IP15 is low: 2 left INFO [com.shoplite.order.OrderService] Order 17 placed by customer 5 --- Logger set to WARNING: one line changes what you see --- WARNING [com.shoplite.order.OrderService] Stock of MOB-IP15 is low: 2 left
What this code does
- The printed lines all look the same: nothing says which one is a problem. The logger lines carry a level and the logger's name, so
WARNINGstands out at once. log.fine(...)is hidden at the defaultINFOlevel, and one call,log.setLevel(Level.WARNING), hides theINFOline too. Theprintlnlines can only be removed by editing the code.
Printed lines have no level, so you cannot tell an error from a detail. You cannot switch them off without editing code. They cannot go to a file, and they carry no time or class name.
A logger fixes all four with configuration, not code changes.
System.out, so the output is the same on every run. Real log lines start with a timestamp.System.Logger and java.util.logging
java.util.logging (JUL) is the logging library built into the JDK. System.Logger, added in Java 9, is the small interface you call, and by default it writes through JUL.
One System.Logger makes five calls, one per level. Predict which lines the program prints before you read the output.
Example 2 · System.Logger: five levels, two hidden
import java.lang.System.Logger;import java.lang.System.Logger.Level;
public class SystemLoggerDemo { static { // only for this page: log lines on System.out, without the date line System.setErr(System.out); System.setProperty("java.util.logging.SimpleFormatter.format", "%4$-7s [%3$s] %5$s%n"); }
private static final Logger log = System.getLogger("com.shoplite.payment.UpiPayment");
public static void main(String[] args) { log.log(Level.TRACE, "Entering pay() for order 17"); log.log(Level.DEBUG, "Calling UPI gateway with timeout 10 s"); log.log(Level.INFO, "Payment of Rs 3097.00 received for order 17"); log.log(Level.WARNING, "UPI gateway slow: answered in 8.4 s"); log.log(Level.ERROR, "Payment for order 18 failed: gateway refused");
System.out.println("DEBUG enabled? " + log.isLoggable(Level.DEBUG)); System.out.println("INFO enabled? " + log.isLoggable(Level.INFO)); }}INFO [com.shoplite.payment.UpiPayment] Payment of Rs 3097.00 received for order 17 WARNING [com.shoplite.payment.UpiPayment] UPI gateway slow: answered in 8.4 s SEVERE [com.shoplite.payment.UpiPayment] Payment for order 18 failed: gateway refused DEBUG enabled? false INFO enabled? true
What this code does
System.getLoggerneeds no library: it is part of the JDK. TheTRACEandDEBUGlines are dropped because the default threshold isINFO.- The
ERRORline prints asSEVERE: the JUL backend uses its own level names.isLoggable(Level.DEBUG)asks the logger whether a level is switched on.
Get a logger with System.getLogger("name") and write with log.log(Level.INFO, "message"). Its levels are TRACE, DEBUG, INFO, WARNING and ERROR.
JUL has its own level names: DEBUG shows up as FINE, TRACE as FINER and ERROR as SEVERE. Out of the box only INFO and above are printed, which is why the TRACE and DEBUG lines never appear.
SLF4J in Spring Boot: TRACE, DEBUG, INFO, WARN, ERROR
SLF4J (Simple Logging Facade for Java) is the logging API that Spring Boot and most Java libraries call. Logback sits behind it and writes the lines.
A Spring service asks for one logger named after its class, then logs at a different level for each event. Watch which lines the default level lets through.
Example 3 · src/main/java/com/shoplite/product/ProductService.java (SLF4J levels)
Runs in: the shoplite-api Spring Boot project
// src/main/java/com/shoplite/product/ProductService.java (the logging parts)package com.shoplite.product;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
@Service@Transactional(readOnly = true)public class ProductService {
private static final Logger log = LoggerFactory.getLogger(ProductService.class);
private final ProductRepository products; private final ShopLiteProperties props;
ProductService(ProductRepository products, ShopLiteProperties props) { this.products = products; this.props = props; }
@Transactional public void takeStock(Product product, int quantity) { log.trace("takeStock({}, {})", product.getId(), quantity); log.debug("Product {} has {} in stock, taking {}", product.getId(), product.getStock(), quantity); if (product.getStock() < quantity) { log.info("Not enough stock of {}: {} requested, {} available", product.getSku(), quantity, product.getStock()); throw new OutOfStockException(product, quantity); } product.setStock(product.getStock() - quantity); if (product.getStock() <= props.lowStockThreshold()) { log.warn("Low stock: {} has {} left", product.getSku(), product.getStock()); } }}2026-10-16T10:42:07.118+05:30 INFO 14872 --- [shoplite-api] [nio-8080-exec-3] com.shoplite.product.ProductService : Not enough stock of MOB-IP15: 9 requested, 8 available 2026-10-16T10:42:19.406+05:30 WARN 14872 --- [shoplite-api] [nio-8080-exec-5] com.shoplite.product.ProductService : Low stock: MOB-IP15 has 2 left
What this code does
LoggerFactory.getLogger(ProductService.class)names the logger after the class, so every line shows where it came from. The{}marks are placeholders; the next lesson covers them.- At the default
INFOlevel thetraceanddebuglines cost almost nothing and print nothing. The refused order isINFO(the customer is told, nothing is broken); the low stock isWARN(someone should reorder).
SLF4J has five levels, from most detail to most serious: TRACE, DEBUG, INFO, WARN, ERROR. A logger set to INFO prints INFO, WARN and ERROR and drops the rest.
Spring Boot's default level is INFO. The {} marks in the example are placeholders; the next lesson covers them.
What belongs at each level
A log level says how serious a line is. A logger prints only the lines at or above its own level.
A checkout logs four different events. Decide which level each one deserves, then compare with the output.
Example 4 · Choosing levels in a checkout
import java.lang.System.Logger;import java.lang.System.Logger.Level;import java.util.List;
record CartLine(String sku, int quantity, int stock) {}
class CheckoutService { private static final Logger log = System.getLogger("com.shoplite.order.CheckoutService"); private int nextOrderId = 17;
void checkout(int customerId, List<CartLine> lines, boolean gatewayUp) { log.log(Level.DEBUG, "Checking " + lines.size() + " cart lines for customer " + customerId); for (CartLine line : lines) { if (line.quantity() > line.stock()) { // the customer asked for too much: expected, the API answers 409 log.log(Level.INFO, "Order refused for customer " + customerId + ": only " + line.stock() + " of " + line.sku() + " in stock"); return; } if (line.stock() - line.quantity() < 3) { log.log(Level.WARNING, "Stock of " + line.sku() + " drops to " + (line.stock() - line.quantity()) + " after this order"); } } if (!gatewayUp) { log.log(Level.ERROR, "Payment gateway unreachable; order for customer " + customerId + " not placed"); return; } log.log(Level.INFO, "Order " + nextOrderId++ + " placed by customer " + customerId); }}
public class CheckoutLevelsDemo { static { // only for this page: log lines on System.out, without the date line System.setErr(System.out); System.setProperty("java.util.logging.SimpleFormatter.format", "%4$-7s %5$s%n"); }
public static void main(String[] args) { CheckoutService service = new CheckoutService(); System.out.println("1) A normal order"); service.checkout(5, List.of(new CartLine("BK-CLEAN", 1, 30)), true); System.out.println("2) The last units of a phone"); service.checkout(1, List.of(new CartLine("MOB-IP15", 2, 4)), true); System.out.println("3) More than the stock"); service.checkout(2, List.of(new CartLine("MOB-IP15", 9, 2)), true); System.out.println("4) Gateway down"); service.checkout(3, List.of(new CartLine("ACC-AD141", 1, 120)), false); }}1) A normal order INFO Order 17 placed by customer 5 2) The last units of a phone WARNING Stock of MOB-IP15 drops to 2 after this order INFO Order 18 placed by customer 1 3) More than the stock INFO Order refused for customer 2: only 2 of MOB-IP15 in stock 4) Gateway down SEVERE Payment gateway unreachable; order for customer 3 not placed
What this code does
- Each case gets the level that matches who must act: nobody (
INFO), the stock team soon (WARNING), or the on-call developer now (ERROR, printed asSEVERE). - The too-much-stock case is
INFO, notERROR: the customer made a normal request that the shop refused, exactly as the API contract says.
Pick the level by asking: who needs this line, and what should they do about it?
ERROR: something failed and a person must act. The payment gateway is unreachable, an order could not be saved.WARN: something odd happened but the app coped. Stock is nearly gone, a retry succeeded, a slow response.INFO: normal business events worth keeping. Order 17 placed, app started. A customer asking for too much stock is alsoINFO: the API answers 409 and nothing is broken.DEBUGandTRACE: details for developers, such as values inside a method or SQL timings. Off in production.
Find the bug
Spot the wrong level
Tap the line whose level does not fit the event.
A customer asks for 9 phones, only 2 are in stock, and the API answers 409.
Round 1 of 2ERROR. If nobody on your team has to fix anything, it is not an error.Changing levels per package
Level inheritance means a logger with no level of its own uses the level of its nearest parent name, such as com.shoplite.order for com.shoplite.order.OrderService, and finally the root.
Logger names form a tree by package. A level set on a package applies to every class below it, unless a deeper setting overrides it.
logging.level.root=warnlogging.level.com.shoplite=infologging.level.com.shoplite.order=debuglogging.level.org.hibernate.SQL=debug# change a level at runtime (needs management.endpoints.web.exposure.include=loggers):# POST /actuator/loggers/com.shoplite.order {"configuredLevel":"TRACE"}Example 5 · DEBUG for one package only
import java.util.logging.Handler;import java.util.logging.Level;import java.util.logging.Logger;
public class PackageLevelsDemo { static { // only for this page: log lines on System.out, without the date line System.setErr(System.out); System.setProperty("java.util.logging.SimpleFormatter.format", "%4$-7s [%3$s] %5$s%n"); }
// keep strong references: JUL may forget the level of a logger nobody holds private static final Logger ORDER_PACKAGE = Logger.getLogger("com.shoplite.order"); private static final Logger orderLog = Logger.getLogger("com.shoplite.order.OrderService"); private static final Logger productLog = Logger.getLogger("com.shoplite.product.ProductService");
static void handleRequests() { orderLog.fine("Order 17: 2 items, total Rs 3097.00"); orderLog.info("Order 17 placed by customer 1"); productLog.fine("Product 6 read from the database in 3 ms"); productLog.info("Product 16 created: sku ACC-KB100"); }
public static void main(String[] args) { System.out.println("--- Default: INFO for everyone ---"); handleRequests();
System.out.println("--- DEBUG (FINE) for com.shoplite.order only ---"); ORDER_PACKAGE.setLevel(Level.FINE); for (Handler h : Logger.getLogger("").getHandlers()) { h.setLevel(Level.ALL); // the console handler filters at INFO on its own } handleRequests(); }}--- Default: INFO for everyone --- INFO [com.shoplite.order.OrderService] Order 17 placed by customer 1 INFO [com.shoplite.product.ProductService] Product 16 created: sku ACC-KB100 --- DEBUG (FINE) for com.shoplite.order only --- FINE [com.shoplite.order.OrderService] Order 17: 2 items, total Rs 3097.00 INFO [com.shoplite.order.OrderService] Order 17 placed by customer 1 INFO [com.shoplite.product.ProductService] Product 16 created: sku ACC-KB100
What this code does
setLevel(Level.FINE)oncom.shoplite.orderturns on detail forOrderService(its child), whileProductServicestays atINFO.- JUL filters twice: at the logger and at the handler that writes the line. The console handler stops at
INFOby itself, so the demo lowers it too. Spring Boot'slogging.level.*does all of this for you.
With Actuator's loggers endpoint you can even change a level while the app runs. That is how teams switch on DEBUG for one package during an incident and switch it off again afterwards.
Predict the output
Which level applies?
The most specific package setting wins.
Round 1 of 2
At which level does com.shoplite.order.OrderMapper log?
Next step
Check your understanding
11 quick questions