Structured logging and metrics
What you will learn
Observability helps us ask why a service behaves as it does. Logs record discrete events, metrics summarize measurements over time, and traces connect work across boundaries. Start with a small, safe telemetry schema for a fictional catalog endpoint.
- Choose logs, counters, gauges and timers for a concrete question.
- Build an allowlisted structured event and bounded metric dimensions.
- Aggregate timer counts and durations with explicit units.
Plain Java examples: save as Main.java in a fresh directory, then run javac --release 21 Main.java and java Main. Standalone Java 21 models; the companion telemetry configuration is source-reviewed, not executed.
Emit an allowlisted event
import java.util.Map;import java.util.Set;public class Main { static String event(String outcome, Map<String,String> input) { String operation = input.get("operation"); if (!"catalog_read".equals(operation) || !Set.of("ok","error").contains(outcome)) throw new IllegalArgumentException("unknown event dimension"); return "event=request_finished operation=" + operation + " outcome=" + outcome; } public static void main(String[] args) { System.out.println(event("ok", Map.of("token","SECRET", "query","private", "operation","catalog_read"))); }}Expected output:
event=request_finished operation=catalog_read outcome=okOnly approved constant tokens enter this illustrative key-value line. A general JSON logger must encode arbitrary strings safely. The input token and query are discarded.
Logs with a stable schema
SLF4J is a facade, not a storage backend. A compatible provider such as Logback renders and transports events. Parameterized calls avoid eager message formatting but do not redact secrets. SLF4J 2 supports fluent key-value logging: logger.atInfo().addKeyValue("operation", "catalog_read").log("request finished"). A provider decides whether these become JSON. Choose stable event names and levels; avoid full URLs, query strings, credentials, raw bodies and personal identifiers. Allowlist data at capture, not only after export. Escape untrusted text with a real structured encoder. Never put heap dumps or raw exception payloads in public logs.
Metrics and dimensions
A counter accumulates nonnegative increments; use its change over an interval for a rate, accounting for process restarts. A gauge samples current state, such as queue length; it can rise or fall. A timer tracks event count and duration; a distribution summary measures non-time values. Micrometer supplies these instruments and registry adapters. Limit labels to bounded sets such as operation and outcome; avoid request IDs, raw paths, user IDs, and arbitrary exception messages. Even a modest number of labels multiplies series counts. Trace IDs may be correlated through supported exemplars rather than ordinary metric labels.
Units and aggregation
Measure elapsed duration with monotonic time (System.nanoTime differences), not wall-clock timestamps. Pass a TimeUnit or Duration to a Micrometer timer; the backend chooses its display unit. For combined mean latency, sum total durations and divide by total count, not by the number of instances. A percentile is not a mean; do not average per-instance p95s. Merge compatible histogram bucket counts for aggregate quantiles, with matching boundaries and time windows. The examples below use explicitly fictional observations, not production measurements.
Bound metric labels
import java.util.List;public class Main { static String route(String path) { return path.matches("/items/[0-9]{1,12}") ? "/items/{id}" : "other"; } public static void main(String[] args) { for(String s : List.of("/items/42","/items/99","/private?secret=x")) System.out.println(route(s)); }}Expected output:
/items/{id}/items/{id}otherUse router-provided templates in a real app. This bounded synthetic mapper emits just two possible labels and never emits raw input.
Aggregate synthetic timer snapshots
public class Main { record Sample(long count,long totalMillis) {} static double mean(Sample a,Sample b) { long count=Math.addExact(a.count(),b.count()); if(count<=0) throw new IllegalArgumentException("no samples"); return (double)Math.addExact(a.totalMillis(),b.totalMillis())/count; } public static void main(String[] args) { var a=new Sample(2,40); var b=new Sample(8,400); System.out.println(mean(a,b)); }}Expected output:
44.0Two requests total 40 ms; eight total 400 ms. Across ten requests the mean is 44 ms, not the unweighted 35 ms. Both snapshots describe non-overlapping observations in the same window.
Common mistakes
Do not log a raw token or use a trace ID as a normal metric tag. Do not treat absence of samples as zero latency. Never compare nanoseconds to milliseconds without conversion.
Practice
Implement a metric key with bounded outcome values success and failure; map anything else to other. Print the keys for success, failure and a synthetic untrusted string.
Expected output:
catalog.requests:successcatalog.requests:failurecatalog.requests:otherCompare with the manual review criteria.
Further reading: SLF4J · Meters · Timers · Cardinality. Independent editorial review remains pending.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Structured logging and metrics — knowledge check
Observability and reliability reasoning.
What does SLF4J supply?
Which label is usually bounded?
What measures current queue depth?
How combine two timer means?
What does parameterized logging guarantee about secrets?