Lesson · Logging
Logging: levels, lazily built messages and structure
13 min readLogging
Logs are the only part of a system that outlives a bug report. Logging well means picking levels that mean something, paying for message building only when it is used, attaching context instead of concatenating strings, and never logging secrets.
Why logging gets its own lesson
A debugger runs once; logs run forever. They are the record of what a system did in production, at 3 a.m., across services, after the fact. That makes every logging line a small API decision: who reads it, at which level, with what context.
Java ships java.util.logging (JUL), and the ecosystem standard is a facade (SLF4J) over an implementation (Logback, Log4j2, JUL). The API in this lesson is JUL's because it needs no dependencies, but the rules transfer one to one: the facade is for the call sites, the implementation is a deployment choice.
Levels are a filter with a contract
Loggers compare each record's level against a threshold and drop everything below it before any formatting happens. The levels form a ladder (JUL: SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST; SLF4J: ERROR, WARN, INFO, DEBUG, TRACE), and the contract is about audience:
- ERROR: the operation failed and someone should act. Include what failed, for which input, with the exception attached.
- WARN: something recoverable happened that operators should notice (retry, fallback, degraded path).
- INFO: the milestones of normal operation: started, stopped, a user-visible transaction completed. Keep it low-volume.
- DEBUG/FINE: diagnosis detail for developers: branch taken, values compared. Off in production by default.
- TRACE/FINEST: everything, including per-item loops. Expect to enable it for one logger, briefly.
Level ladder · pick the production threshold
logger level: INFO = INFOwhat this threshold lets through
eager concat pays always
log.fine("state: " + dumpGraph(object));
dumpGraph runs even when FINE is filtered: the string is built before the check.
parameterized pays only when logged
log.log(Level.FINE, "user 0 action 1", args);
placeholders fill after the level check; filtered records cost almost nothing.
Message construction is the cost you can skip
String concatenation happens before the log call, which means it happens even when the message is dropped. A debug line inside a hot loop that builds strings from the object graph is a performance bug disguised as a diagnostic.
Two mechanisms fix it: parameterized messages, where the logger formats placeholders only after the level passes, and an explicit isLoggable guard around genuinely expensive arguments. Both push the work behind the level check.
log.log(Level.FINE, "user {0} action {1}", new Object[]{user, action}); // formatted only if logged if (log.isLoggable(Level.FINE)) { log.fine(() -> "state: " + dump()); } // expensive build guarded
Attach the exception, name the context
A log line about a failure without the exception loses the stack trace, and a message that only repeats the exception text loses the context. The pattern that carries both: log at the boundary with a human sentence and the throwable as the last argument, letting the handler print the trace.
For cross-cutting context (request id, user id, tenant), appenders apply a layout that includes it on every line rather than every call site pasting it into messages. Correlation ids turn a scattered log into a timeline.
log.log(Level.WARNING, "order 8123 failed to settle", e); // message plus full trace logger.atInfo().addKeyValue("orderId", id).log("settled"); // SLF4J fluent style
The house rules
These survive every framework choice and every rebrand of the ecosystem:
- Never log secrets or personal data. Passwords, tokens, session ids, card numbers, full request bodies: once logged, they are forever. Log shapes (token length, last four digits).
- One event per line. Multi-line blobs break greppers and log pipelines; push structured data into key-value fields.
- Structured over prose for pipelines. Key-value or JSON output (event name plus fields) parses without regex; prose is for humans and is still allowed at INFO.
- No logging in tight loops at INFO. Aggregate first; the loop-level detail belongs to TRACE.
- Test the contract. A handler that captures records lets a unit test assert what was logged, at which level, without reading console output.
The review question for every log line: who acts on this, and what do they do? If the answer is nobody, the line is noise, and noise is why real alerts get ignored.
Logs are API for the future
The reader is a tired engineer at 3 a.m. with no debugger and no context. Levels tell them what to read, structure tells the tools what to parse, and the exception tells both of them where it went wrong.
Interview angles
Why is building log strings eagerly a problem?+
The concatenation runs before the logger can drop the record, so filtered levels still pay for formatting and object traversal. Parameterized messages and isLoggable guards move that work behind the level check.
What belongs at ERROR versus WARN?+
ERROR is an operation that failed and needs action; WARN is something recoverable that operators should be aware of (retry succeeded, fallback used). If nothing should be done, it is INFO at most.
How should exceptions be logged?+
Pass the throwable as an argument to the log call at the boundary where context exists; the handler renders message and stack trace together. Never log e.getMessage() alone: the trace is the point.
What must never appear in logs?+
Secrets and personal data: credentials, tokens, session ids, personal identifiers, full card numbers. Log lengths, counts, hashes or masked forms, and treat log storage as a data-protection surface.
Facade versus implementation in logging?+
Applications log against a facade (SLF4J); the implementation (Logback, Log4j2, JUL) is a deployment decision behind it. The facade keeps call sites dependency-light and lets operations switch backends without a recompile.