skip to content

Logging & Observability

Logging frameworks and metrics facades across the JVM, .NET, Node and Go ecosystems. Interviewers ask because structured output and a stable facade are what make logs and metrics usable once you run more than one service.

on this pageshow

explore

questions

page 1 of 2

In Logback, walk through what happens between a call to logger.info(...) and a line appearing in a file: how the event reaches appenders, what additivity does, and how an encoder differs from a layout.

level: juniorimportance: must knowfreq 60%

answer

  1. effective level = own or nearest ancestor; root always set
  2. event carries MDC copy + lazy caller data
  3. additivity walks up to root — duplicates
  4. filter ACCEPT/DENY/NEUTRAL per appender
  5. encoder owns bytes/charset; layout is legacy

basics

~20 s

The logger checks its effective level, builds a LoggingEvent, then walks up the logger hierarchy appending to every appender attached along the way (additivity). Each appender runs its filters, then an encoder turns the event into bytes and writes them.

solid answer

~50 s

The call first hits a level check against the logger's **effective level** — its own level, or the nearest ancestor's if unset; root always has one, so the check is always defined. If it passes, Logback builds a `LoggingEvent` carrying level, logger name, message pattern, argument array, thread, timestamp, a copy of the MDC and an optional throwable. The event is then given to the appenders attached to that logger and — because **additivity** defaults to true — to appenders on every ancestor up to root. That is why adding a FILE appender to `com.acme` while root holds CONSOLE yields both; `additivity="false"` stops the walk at that logger and is the standard fix for duplicated lines. Inside an appender, attached filters vote, then the **encoder** converts the event to bytes and writes to the output stream. `Layout` (event → String) is the older abstraction; the encoder owns bytes, charset and line separator, which is why `PatternLayoutEncoder` (or a JSON encoder) is what you configure today.

code

text · 8 lines
text
logger com.acme.billing  -> [FILE]      additivity=true
logger ROOT              -> [CONSOLE]

info("paid") on com.acme.billing.Invoice
  -> FILE     (from com.acme.billing)
  -> CONSOLE  (from ROOT, via additivity)

set additivity=false on com.acme.billing -> FILE only

go deeper

for a junior

Be able to state the sequence: level check, event, appenders up the hierarchy, filters, encoder writes. Know that additivity explains duplicate lines.

for a middle

Add the effective-level resolution rule, the eager MDC copy versus lazy caller data, and why the parameterised call form matters.

for a senior

Discuss the cost model — immediateFlush, caller-data converters, appender locking — and use additivity deliberately to route audit or access logs to a single destination.

for a principal

Treat the appender graph as a routing topology: shared appender instances, per-destination filters and structured encoders as the contract with downstream log processing, and set org-wide conventions rather than per-service patterns.

## The pieces Logback consists of a `LoggerContext` (one configured world per application), `Logger` objects named by dot-separated strings and arranged in a hierarchy from that naming, `Appender`s that are output destinations, and `Encoder`s that serialise an event. `LoggerFactory.getLogger("com.acme.billing.Invoice")` returns a logger whose ancestors are `com.acme.billing`, `com.acme`, `com` and `ROOT`. The hierarchy is purely lexical — nothing scans classes. ## Level check first Every logger has an optional assigned level and an **effective level**: the assigned one, else the nearest ancestor's. `ROOT` is always assigned (DEBUG by default), so resolution terminates. The check is a cheap integer comparison and is why the parameterised form `log.debug("user {} failed", id)` matters: with a disabled level, no string concatenation and no `toString()` happen, because the arguments are only formatted after the check passes. ## Building the event A passing call materialises a `LoggingEvent`. Two fields deserve attention. The **MDC** is copied into the event at creation time, so a value put on the thread after the call is not visible in that line, and an asynchronous handoff later still carries the values captured here. **Caller data** (class, method, file, line) is *not* captured eagerly — deriving it requires walking the stack, so Logback computes it lazily only if the pattern asks (`%class`, `%method`, `%line`, `%caller`). Those converters are the classic reason a hot logging path is slow. ## Appender walk and additivity The event is passed to `callAppenders`, which iterates the current logger's appenders, then repeats on the parent, and so on up to root — unless a logger has `additivity="false"`, which ends the walk after its own appenders run. Consequences worth stating in an interview: - **Duplicate lines** almost always mean an appender is attached to both a specific logger and root with additivity left on. - Additivity is not a level. A logger with `additivity="false"` and no appenders of its own drops the event entirely, which is a common accidental silencing. - The same appender instance can be referenced from several loggers; it is shared, so its filters and its output ordering apply to all of them. ## Filters, then encoder Each appender may carry filters returning `ACCEPT` (write immediately, skipping remaining filters), `DENY` (drop) or `NEUTRAL` (keep evaluating; if all are neutral the event is written). This is a per-destination decision, distinct from the logger level, so one appender can be noisier than another for the same event stream. The surviving event goes to the encoder. Historically `Layout` produced a `String` and the appender decided how to write it; since Logback 0.9.19 `Encoder` owns the event-to-bytes step, including charset, the trailing separator and any header/footer. `PatternLayoutEncoder` is a bridge that wraps a `PatternLayout`; structured logging simply swaps in a JSON encoder without touching the appender. Practically: configure `<encoder>`, not `<layout>`. ## Where writes actually land `OutputStreamAppender` (the parent of console and file appenders) writes under a lock and, by default, flushes each event — safe but syscall-heavy. `immediateFlush=false` buffers and multiplies throughput at the cost of losing the tail on a hard kill. That trade-off, not the pattern string, is what usually explains logging cost in a benchmark.

  • Why is log.debug("id={}", id) preferable to log.debug("id=" + id)?
    With the placeholder form, the argument array is passed by reference and formatting happens only after the level check passes, so a disabled DEBUG level costs one integer comparison. String concatenation is evaluated by the caller before the method is even entered, so it pays for concatenation and any toString() regardless of level. It also keeps the message pattern constant, which structured encoders and log aggregators can group on.
  • A team sees every line twice in the console. What do you check?
    Almost always additivity: an appender attached to an application logger while the same appender or an equivalent console appender is also on root, so the event is written on the way up. Fix by setting additivity="false" on the specific logger, or by removing the duplicate appender reference rather than the logger. Also confirm two logging backends are not both on the classpath, which produces a similar symptom for a different reason.

Additivity is a memo dropped into a mail chute: it passes every floor's inbox on the way down to the lobby unless someone seals the chute on their floor.

  • Thinking additivity is a level or a filter rather than the parent-appender walk
  • Claiming a logger with no level configured logs nothing — it inherits its ancestor's
  • Believing caller data (%line, %method) is free because it appears in a pattern
  • Saying the MDC is read when the line is written, so late puts show up
  • Configuring <layout> and assuming charset and line-separator handling come with it

Encoder replaced Layout as the configured element in Logback 0.9.19+; applies to the 1.2, 1.3 and 1.5 lines alike.

context

open as a page

Micrometer offers Counter, Gauge, Timer and DistributionSummary. Explain how you choose between them for a given measurement, and why a Micrometer Gauge must be registered against an object it observes rather than being set imperatively.

level: juniorimportance: must knowfreq 58%

basics

~20 s

Counter is a monotonically increasing total you consume as a rate. Gauge is a value sampled at publish time that can go up or down. Timer records durations plus a count. DistributionSummary records non-time distributions. A Gauge holds the observed object weakly and reads it on publish, so instrumentation never keeps it alive.

open as a page

What do morgan's predefined formats dev, tiny, short, common and combined log, and which suits local development versus a production access log?

level: juniorimportance: must knowfreq 35%

basics

~20 s

morgan's dev format prints method, URL, a status colored by class, response time and body size for local work. tiny and short are compact timed lines; common and combined follow the classic web-server log layouts, combined adding referrer and user agent.

open as a page

In an ASP.NET Core 10 app, what does builder.Services.AddSerilog() change about ILogger<T> logging, and what happens to the Logging section and built-in providers?

level: juniorimportance: must knowfreq 65%

basics

~20 s

AddSerilog() registers Serilog's ILoggerFactory, so every ILogger<T> writes through the Serilog pipeline, with the category as SourceContext. Levels then come from Serilog's MinimumLevel and overrides; the Logging section and the built-in console and debug providers are bypassed.

open as a page

In Serilog 4, how do you build a LoggerConfiguration that writes to the console and a daily file, and what is the default minimum level?

level: juniorimportance: must knowfreq 70%

basics

~10 s

Chain new LoggerConfiguration(), WriteTo.Console() and WriteTo.File(path, rollingInterval: RollingInterval.Day), then CreateLogger(), after adding Serilog.Sinks.Console and Serilog.Sinks.File. With no MinimumLevel call, Information and above pass; Debug and Verbose are dropped.

open as a page

In Serilog, how does Log.Information("Shipment {TrackingNumber} picked up by {CourierId}", number, courierId) bind its arguments, and why is an interpolated string wrong?

level: juniorimportance: must knowfreq 70%

basics

~20 s

Serilog parses the template, then assigns the arguments to its named holes in order: number becomes TrackingNumber, courierId becomes CourierId. An interpolated string bakes the values into the template text: no properties, and a new template per value.

open as a page

In SLF4J, how does a servlet filter scope an MDC request id to one request, and when should it use MDC.remove versus MDC.clear?

level: juniorimportance: must knowfreq 60%

basics

~20 s

Put the id with MDC.putCloseable inside try-with-resources, or call MDC.remove in a finally block, so the entry leaves the thread when the request ends. remove drops only your key; clear wipes every entry on the thread.

open as a page

Why do SLF4J log calls use a message with `{}` placeholders and separate arguments instead of building the message with string concatenation, and when do you still need an `isDebugEnabled()` guard?

level: juniorimportance: must knowfreq 80%

basics

~20 s

Placeholders defer formatting: if the level is disabled, the arguments are never converted to strings and no message is built. Concatenation pays that cost on every call. You only need an enabled-check when computing an argument is itself expensive.

open as a page

How does Logback find and load its configuration at startup, what is the precedence between logback-test.xml, logback.xml and the logback.configurationFile system property, and how do you debug a configuration that appears to be ignored?

level: middleimportance: must knowfreq 55%

basics

~20 s

On first use of a logger, Logback auto-configures: the logback.configurationFile system property wins, else logback-test.xml, else logback.xml on the classpath; with none, it falls back to a console appender at DEBUG. Its own parse errors go to an internal status list, printable via a status listener.

open as a page

In Micrometer, a meter is identified by its name plus a set of tags (key/value dimensions). What makes a tag safe or unsafe to add, and what exactly breaks — in the application process, at export/scrape time, and in the metrics backend — when tag cardinality is unbounded?

level: middleimportance: must knowfreq 52%

basics

~20 s

A tag is safe when its value set is bounded and decided by your code, not by callers. Each distinct tag combination is a permanent time series: registry memory that is never reclaimed, a larger export payload, backend index growth, and slower queries.

open as a page

With morgan, how do you add a request id to every access-log line, and when do you need morgan.token rather than the built-in :req[header] token?

level: middleimportance: must knowfreq 30%

basics

~20 s

If the id arrives in a request header, the built-in :req[x-request-id] token prints it. If your code generates the id and stores it on req, register morgan.token('id', (req) => req.id) once and put :id in the format string.

open as a page

What does Serilog.AspNetCore's UseSerilogRequestLogging() log for each request, at which level, and why does its position in the middleware pipeline matter?

level: middleimportance: must knowfreq 60%

basics

~20 s

It writes one event per request: "HTTP {RequestMethod} {RequestPath} responded {StatusCode} in {Elapsed:0.0000} ms", at Error when an exception escapes or the status exceeds 499, else Information. It only times and logs middleware registered after it.

open as a page

In a Serilog message template, how do {Shipment}, {@Shipment} and {$Shipment} differ, and what does @ cost on a large object?

level: middleimportance: must knowfreq 60%

basics

~10 s

Plain {Shipment} keeps scalars and collections but stores ToString() for other objects; {@Shipment} destructures public properties recursively, to depth 10; {$Shipment} always stores ToString(). @ costs reflection, every getter run, and graph-sized payloads.

open as a page

What problem does the SLF4J logging facade solve on the JVM, and how does an application end up bound to one concrete logging backend at runtime?

level: middleimportance: must knowfreq 70%

basics

~20 s

SLF4J is an API-only jar that libraries compile against. At startup it discovers one provider on the classpath and delegates every call to it. The application, not the library, picks the backend; with no provider, logging becomes a no-op.

open as a page

With SLF4J's MDC, how do you carry a request id into ExecutorService tasks and CompletableFuture stages, and what must the task's finally do?

level: middleimportance: must knowfreq 55%

basics

~10 s

Capture MDC.getCopyOfContextMap() when the task is submitted, apply it with MDC.setContextMap inside the task, and in finally restore the worker's previous map, clearing when it was null, so no request's entries stay behind.

open as a page

In SLF4J 2.0, how does the formatter decide whether a log call's last argument is the exception to print with its stack trace?

level: middleimportance: must knowfreq 61%

basics

~20 s

When a call passes two or more arguments and the last is a Throwable, SLF4J 2.0 strips it off and logs it as the cause, however many {} anchors remain. An exception in any other position is a plain value, printed via toString().

open as a page

Why can a Serilog-based .NET app lose its last log events on exit or after a crash, and how does Log.CloseAndFlushAsync() prevent it?

level: seniorimportance: must knowfreq 55%

basics

~20 s

Batched, buffered and async sinks hold events in memory and write them later, so exiting without disposing the logger abandons them. Log.CloseAndFlushAsync() disposes the static logger, draining those sinks, and resets Log.Logger; await it in finally.

open as a page

What do SLF4J 2.0's own startup lines, such as 'Actual provider is of type [...]', tell you, and what does slf4j.internal.verbosity change?

level: juniorimportance: should knowfreq 40%

basics

~10 s

SLF4J prints its own SLF4J(I)/SLF4J(W) lines to stderr about binding: no provider, several providers, and 'Actual provider is of type', naming the winner. slf4j.internal.verbosity (default INFO) filters those lines, never application logs.

open as a page

In SLF4J 2.0's fluent API, why does a logger.atWarn() chain that never calls log() print nothing, and when do you use setCause()?

level: juniorimportance: should knowfreq 40%

basics

~20 s

Builder methods such as addArgument and addKeyValue only record data on a pending event; log() hands it to the backend, so a chain without it logs nothing. setCause attaches the exception directly, not as a trailing argument.

open as a page

In SLF4J placeholder logging, how do you print a literal `{}` in a message, and how are null values and array arguments rendered?

level: juniorimportance: should knowfreq 52%

basics

~20 s

Put a backslash before the brace, written \{} in a Java string literal, and SLF4J prints {} without using up an argument. A null argument prints as null; arrays print as [a, b], except a reference-type array passed alone, which becomes the argument list.

open as a page

Logback lets you suppress a log event with a logger level, a TurboFilter on the context, or a Filter attached to an appender. Explain where each one runs, what it can see, and how you would use them to keep one noisy MDC-tagged request at DEBUG while everything else stays at WARN.

level: middleimportance: should knowfreq 42%

basics

~20 s

Level checks are cheapest and happen first, before any event object exists. TurboFilters run next, context-wide, on the raw arguments and MDC, and can force acceptance regardless of level. Appender filters run last, per destination, on the fully built event.

open as a page

With morgan's skip option, how do you keep health-check requests out of the access log, and why can a test on req.url miss them?

level: middleimportance: should knowfreq 25%

basics

~20 s

Pass skip: (req) => req.originalUrl.split('?')[0] === '/health'. morgan calls skip when the line is due, after the response finishes; if a router mounted at /health sent it, req.url can still read '/' then, while req.originalUrl keeps the full path.

open as a page

With Serilog.AspNetCore, how do IDiagnosticContext.Set and RequestLoggingOptions.EnrichDiagnosticContext add user and tenant ids to the single request completion event?

level: middleimportance: should knowfreq 45%

basics

~10 s

Inject IDiagnosticContext and call Set("BookingId", id) during the request, or set common values centrally in RequestLoggingOptions.EnrichDiagnosticContext; both become properties of that request's one completion event only, not of other log events.

open as a page

With Serilog.Settings.Configuration, how is the "Serilog" section of appsettings.json read, and which parts of it change at runtime when the file is edited?

level: middleimportance: should knowfreq 55%

basics

~20 s

ReadFrom.Configuration(configuration) maps the Serilog section onto LoggerConfiguration: WriteTo entries become sink method calls with Args as named parameters, MinimumLevel becomes levels and overrides. On reload, only existing level values change; new Override keys and sink changes need a restart.

open as a page

In Serilog, how do MinimumLevel.Override, a sink's restrictedToMinimumLevel and a LoggingLevelSwitch decide whether an event from a given SourceContext is written?

level: middleimportance: should knowfreq 50%

basics

~20 s

MinimumLevel.Override sets the effective minimum for events whose SourceContext starts with a namespace, replacing the default level. A sink's restrictedToMinimumLevel filters further but cannot let through events the logger dropped. A LoggingLevelSwitch makes either level changeable at runtime.

open as a page

When a Serilog sink silently writes nothing, how does SelfLog help you find out why, and what kinds of problems does it report?

level: middleimportance: should knowfreq 30%

basics

~20 s

Serilog never lets a logging failure throw into the app; it reports it to SelfLog, which is off by default. Calling SelfLog.Enable(Console.Error) before the logger is built prints misnamed sinks, unopenable files and sink exceptions.

open as a page

In Serilog, how do Enrich.WithProperty, ForContext and LogContext.PushProperty attach a property such as a shipment id, and why does PushProperty need Enrich.FromLogContext()?

level: middleimportance: should knowfreq 50%

basics

~20 s

Enrich.WithProperty adds a fixed property to every event, ForContext returns a logger whose events carry it, and LogContext.PushProperty adds it to all events in an async scope until disposed. PushProperty only reaches events if Enrich.FromLogContext() is configured.

open as a page

In SLF4J 2.0's fluent API, when is a Supplier passed to addArgument() or addKeyValue() actually invoked, and what still runs eagerly?

level: middleimportance: should knowfreq 35%

basics

~20 s

On a disabled level, atDebug() returns a no-op builder that never calls the Supplier. On an enabled level, DefaultLoggingEventBuilder calls get() at once inside addArgument or addKeyValue, not at formatting time. Plain argument expressions always run before the call.

open as a page

With jul-to-slf4j on the classpath, how do you install SLF4JBridgeHandler so java.util.logging records reach SLF4J, and how are JUL levels mapped?

level: middleimportance: should knowfreq 38%

basics

~10 s

Call SLF4JBridgeHandler.removeHandlersForRootLogger(), then SLF4JBridgeHandler.install(), once at startup, or name the handler in logging.properties. FINEST maps to TRACE, FINER and FINE to DEBUG, CONFIG and INFO to INFO, WARNING to WARN, SEVERE to ERROR.

open as a page

What is SLF4J's Mapped Diagnostic Context (MDC), and why does putting a correlation identifier into it often produce missing or wrong values in a service that uses thread pools and asynchronous work?

level: middleimportance: should knowfreq 55%

basics

~20 s

MDC is a per-thread key-value map that the layout can print on every line, so you set a correlation id once instead of passing it to every log call. It is thread-local: work handed to another thread does not inherit it, and a pooled thread keeps stale entries unless cleared.

open as a page

showing 1–30 of 49