Command Palette

Search for a command to run...

Back to the lesson: Topic 15.6 — Logging Done Right
Core Java · Example 1 of 3 Java 5+

java.util.logging: levels and the logger hierarchy

pricing has no level of its own (null), so it uses its parent's. Changing shop.orders to FINE switched on FINE for the whole subtree: the same idea as a <logger name="com.shop.orders"> line in logback.xml.

Logging records what a running program did, so you can understand it in production where there's no debugger. Professional Java code logs through the SLF4J API with a back-end such as Logback, uses levels (TRACE to ERROR) to control volume, writes parameterized messages (log.info("Order {} placed", id)) instead of string concatenation, and passes exceptions as the last argument so their stack traces are kept.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a JUL Formatter subclass that formats records as LEVEL|logger|message and use it with your own handler to log three messages at different levels.

02

Write a method mask(String card) that keeps only the last four digits ("** ** 4242") and log a payment with the masked card number.

03

Write a JUL handler that counts records per level in a TreeMap and prints the counts after logging five messages.

Explain it without notes

01

Why use a logging framework instead of System.out.println?

02

Why should you write log.debug("x {}", x) instead of log.debug("x " + x)?

03

How should an exception be logged, and what goes wrong otherwise?

04

What is SLF4J, and why do libraries depend on it instead of on Logback?

05

What is the MDC, and what is the common bug when using it with thread pools?

java.util.logging: levels and the logger hierarchy Java 5+
Sign in to run this example in your browser.

Expected output

SEVERE  [shop.orders] payment gateway unreachable
WARNING [shop.orders] retrying payment, attempt 2
INFO    [shop.orders] order A-1042 placed
INFO    [shop.orders] order A-1043 has 3 items
pricing's parent: shop.orders
pricing's own level: null
FINE enabled for pricing? false
INFO    [shop.orders.pricing] price rules loaded
FINE    [shop.orders.pricing] now FINE is on for the whole shop.orders tree