Skip to lesson

Practice: logging

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

A log with the wrong level, a lost stack trace, a leaked secret or lines nobody can connect fails you exactly when ShopLite breaks. Four short checks, each with a fix you can apply line by line.

Mistake 1: the wrong level

Six log lines are audited below, each with the level it has and the level it needs.

Example 1 · Auditing the levels of six log lines

LevelAuditDemo.javaJava
import java.util.List;
public class LevelAuditDemo {    record LogLine(String level, String message, String betterLevel, String why) {    }
    public static void main(String[] args) {        List<LogLine> lines = List.of(                new LogLine("ERROR", "Product 99 was not found", "INFO",                        "a normal 404 for the client"),                new LogLine("INFO", "Entering OrderService.place()", "TRACE",                        "developer detail"),                new LogLine("INFO", "Order 18 placed by customer 7", "INFO",                        "a business event"),                new LogLine("DEBUG", "Payment gateway unreachable, order 17 not placed", "ERROR",                        "money is stuck, someone must act"),                new LogLine("ERROR", "Retry 1 of 3 to the SMS gateway succeeded", "WARN",                        "it worked, but something is flaky"),                new LogLine("WARN", "Validation failed: price must be greater than 0", "DEBUG",                        "the client sent bad data; the 400 answer says so"));
        int changed = 0;        for (LogLine line : lines) {            boolean ok = line.level().equals(line.betterLevel());            if (!ok) {                changed++;            }            System.out.printf("%-5s -> %-5s %s  (%s)%n", line.level(), line.betterLevel(),                    line.message(), ok ? "keep" : line.why());        }        System.out.println(changed + " of " + lines.size() + " lines had the wrong level");    }}
Output
ERROR -> INFO  Product 99 was not found  (a normal 404 for the client)
INFO  -> TRACE Entering OrderService.place()  (developer detail)
INFO  -> INFO  Order 18 placed by customer 7  (keep)
DEBUG -> ERROR Payment gateway unreachable, order 17 not placed  (money is stuck, someone must act)
ERROR -> WARN  Retry 1 of 3 to the SMS gateway succeeded  (it worked, but something is flaky)
WARN  -> DEBUG Validation failed: price must be greater than 0  (the client sent bad data; the 400 answer says so)
5 of 6 lines had the wrong level

What this code does

  • Five of six lines were wrong in both directions: normal client mistakes were too loud, and a real payment failure was hidden at DEBUG.
  • The reason column is the "who must act" test written out. Use it whenever a level is not obvious.

A wrong level makes the log lie about how serious something is. A client's 404 logged as ERROR wakes people up for nothing; a payment failure logged at DEBUG is invisible in production.

Ask one question for every line: who must act, and how soon? Now means ERROR, soon means WARN, nobody means INFO for business events and DEBUG/TRACE for developer detail. Review: What to log at each level (opens in a new tab)

Mistake 2: joined strings and lost stack traces

log.error("Sync failed: " + e.getMessage()) makes two mistakes at once. The next example shows it before and after the fix.

Example 2 · A nightly sync: before and after

StockSyncDemo.javaJava
import java.util.logging.Level;import java.util.logging.Logger;
class WarehouseException extends RuntimeException {    WarehouseException(String message, Throwable cause) {        super(message, cause);    }}
public class StockSyncDemo {    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%6$s%n");    }
    private static final Logger log = Logger.getLogger("com.shoplite.product.StockSync");
    static int readWarehouseStock(String sku) {        throw new IllegalStateException("warehouse API answered 503");    }
    static int syncBefore(String sku) {        try {            return readWarehouseStock(sku);        } catch (IllegalStateException e) {            log.severe("Sync failed for " + sku + ": " + e.getMessage());   // joined text, no stack trace            throw e;        }    }
    static int syncAfter(String sku) {        try {            return readWarehouseStock(sku);        } catch (IllegalStateException e) {            throw new WarehouseException("Stock sync failed for " + sku, e);        }    }
    public static void main(String[] args) {        System.out.println("--- Before ---");        try {            syncBefore("MOB-IP15");        } catch (IllegalStateException e) {            log.severe("Nightly sync stopped: " + e.getMessage());        }
        System.out.println("--- After ---");        try {            syncAfter("MOB-IP15");        } catch (WarehouseException e) {            log.log(Level.SEVERE, "Nightly sync stopped", e);   // once, with the whole chain        }    }}
Output
--- Before ---
SEVERE  Sync failed for MOB-IP15: warehouse API answered 503
SEVERE  Nightly sync stopped: warehouse API answered 503
--- After ---
SEVERE  Nightly sync stopped
WarehouseException: Stock sync failed for MOB-IP15
	at StockSyncDemo.syncAfter(StockSyncDemo.java:35)
	at StockSyncDemo.main(StockSyncDemo.java:49)
Caused by: java.lang.IllegalStateException: warehouse API answered 503
	at StockSyncDemo.readWarehouseStock(StockSyncDemo.java:19)
	at StockSyncDemo.syncAfter(StockSyncDemo.java:33)
	... 1 more

What this code does

  • Before: two lines for one failure, both with only the message, so nobody can see where it failed.
  • After: the lower method adds the SKU by wrapping, and the top logs once with the full chain, including the warehouse's 503 as Caused by.

The joined string is built even when the level is off, and only the message is kept: the exception type, the failing lines and the cause are gone.

Use placeholders, pass the exception last, and log it in one place. Lower layers wrap the exception with context and throw it on; they do not log it too. Review: Parameterised log messages (opens in a new tab)

Mistake 3: secrets and raw user text

Logging a whole record prints every field. Here an address save leaks personal data, and a label forges a log line.

Example 3 · An address save: personal data and a forged line

AddressLogDemo.javaJava
record Address(int id, int customerId, String line1, String city, String pincode) {}
public class AddressLogDemo {    static String safe(String userText) {        String oneLine = userText.replace("\r", "\\r").replace("\n", "\\n");        return oneLine.length() > 40 ? oneLine.substring(0, 40) + "..." : oneLine;    }
    public static void main(String[] args) {        Address home = new Address(10, 8, "4 Residency Road", "Bengaluru", "560025");        String label = "Home\nINFO  Customer 8 is now an ADMIN";
        System.out.println("--- Before ---");        System.out.println("INFO  Address saved: " + home + " label=" + label);
        System.out.println("--- After ---");        System.out.println("INFO  Address " + home.id() + " saved for customer " + home.customerId()                + " in " + home.city() + ", label=" + safe(label));    }}
Output
--- Before ---
INFO  Address saved: Address[id=10, customerId=8, line1=4 Residency Road, city=Bengaluru, pincode=560025] label=Home
INFO  Customer 8 is now an ADMIN
--- After ---
INFO  Address 10 saved for customer 8 in Bengaluru, label=Home\nINFO  Customer 8 is now an ADMIN

What this code does

  • Before: the record's toString() wrote the full street address, and the label's line break produced a fake "now an ADMIN" line.
  • After: ids and the city are enough to investigate, and the escaped label stays inside one line.

Logging an object or record prints every field through toString(), including addresses, phone numbers and passwords. Raw user text can carry a line break that forges a new log line.

Log ids and the few fields you need, mask what must be shown, and escape \r and \n in anything a user typed. Review: What never to log (opens in a new tab)

Mistake 4: lines you cannot connect

Nine lines from three requests are mixed in one log. Group them by the request id to read each story.

Example 4 · Summarising each request from an interleaved log

RequestSummaryDemo.javaJava
import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;
public class RequestSummaryDemo {    static final List<String> LOG = List.of(            "10:42:01.114 INFO  [c9d1] GET /api/v1/products started",            "10:42:01.117 INFO  [e5a0] POST /api/v1/auth/login started",            "10:42:01.131 INFO  [c9d1] GET /api/v1/products -> 200 in 17 ms",            "10:42:01.204 INFO  [e5a0] Login failed for a***@example.com",            "10:42:01.206 INFO  [a1f3] POST /api/v1/me/orders started",            "10:42:01.209 INFO  [e5a0] POST /api/v1/auth/login -> 401 in 92 ms",            "10:42:01.250 WARN  [a1f3] Low stock: MOB-IP15 has 2 left",            "10:42:11.249 ERROR [a1f3] Payment failed for order 17 (Rs 499.00)",            "10:42:11.252 INFO  [a1f3] POST /api/v1/me/orders -> 500 in 10046 ms");
    static String idOf(String line) {        int open = line.indexOf('[');        return line.substring(open + 1, line.indexOf(']', open));    }
    public static void main(String[] args) {        Map<String, List<String>> byRequest = new LinkedHashMap<>();   // keeps first-seen order        for (String line : LOG) {            byRequest.computeIfAbsent(idOf(line), id -> new ArrayList<>()).add(line);        }        for (Map.Entry<String, List<String>> e : byRequest.entrySet()) {            List<String> lines = e.getValue();            String last = lines.get(lines.size() - 1);            String result = last.substring(last.indexOf("->") + 3);            long problems = lines.stream().filter(l -> l.contains(" WARN ") || l.contains(" ERROR ")).count();            System.out.printf("%s: %d lines, %s, %d warning/error line(s)%n", e.getKey(), lines.size(), result, problems);        }    }}
Output
c9d1: 2 lines, 200 in 17 ms, 0 warning/error line(s)
e5a0: 3 lines, 401 in 92 ms, 0 warning/error line(s)
a1f3: 4 lines, 500 in 10046 ms, 2 warning/error line(s)

What this code does

  • Grouping by the id in [...] turns nine mixed lines into three request stories; a LinkedHashMap keeps them in the order they started.
  • Request a1f3 stands out: a 500 after 10 seconds, with a warning and an error inside it. That is the one to read line by line.

In a busy log, a line without a request id is a clue you cannot use. Missing ids usually mean the filter does not run first, the MDC is not copied into async work, or it is not cleared and an old id sticks to new lines.

With ids in place, troubleshooting becomes a routine: find the error line, take its id, pull every line with that id, and read the request's story in order. Review: Request ids to trace one request (opens in a new tab)

Finish up

Mark complete & continue

Next: Mini project: request logging for ShopLite