"Design a logging framework" sounds like a printing problem. A weak answer has a Logger class with an info method that calls System.out.println, adds a level field, and stops. That code works until debug logging is needed for the payments code only, or one thread's stack trace lands in the middle of another's. It also fails when the disk slows down and every request thread waits for it.
The interviewer is checking whether you can keep a small, hot path cheap and safe. Logging runs inside everyone else's code. A disabled line must cost almost nothing, a broken log file must never break a payment, and a background writer must not reorder what it was given or lose it without counting it.
This article follows the 45 minute interview: questions first, then the classes, then the design one decision at a time. Every snippet comes from a complete Java project that compiles and runs, and the Open file button on a snippet opens the whole file.
Ask before you design
Each question below changes the code.
| Question | What we assume | What it changes |
|---|---|---|
| Is this a library inside one service, or a log shipping system? | A library inside one Java service | Everything lives in memory in one process; shipping logs to a server is out of scope |
| Can levels differ for parts of the code? | Yes, by dotted name: app.payments can be at DEBUG while the rest is at INFO | Loggers form a tree, and a logger without a level uses its parent's |
| Where do lines go? | Console, a file, and a JSON feed for alerts, each with its own minimum level | An Appender interface, each appender with a threshold and a format |
| Can a log call ever make the caller fail or wait? | No. A full disk or a slow store must not slow or break the caller | Appender failures are caught and counted; slow appenders go behind a queue |
| Must a disabled line be cheap? | Yes, debug lines stay in hot paths | A level check before any work, and messages built only when needed |
| Can levels change while the service runs? | Yes, to switch on debug for one area during an incident | Levels are read on every call, and a change must reach other threads |
| What happens when the background queue is full? | Drop new records and count them | A bounded queue and a counter instead of a blocked caller |
| Must close lose nothing? | Every record accepted before close is written | close drains the queue before it stops the writer |
| Many threads? | Yes, every request thread logs | Shared appenders must keep records whole, and nothing may be lost or written twice |
The question that matters most is the fourth. Logging is a safety net that runs inside payments, orders and everything else. If the log can throw, block or loop, then the safety net can take down the thing it watches. Most of the decisions below exist to keep that from happening.
Requirements
What the code must do:
- Hand out loggers by dotted name. A logger with no level of its own uses the nearest parent's level, and the root logger always has one.
- Log at TRACE, DEBUG, INFO, WARN and ERROR. A call below the logger's level does no work beyond the check, and a message given as a
Supplieris never built. - Send each record to the appenders on its logger and on every logger above it. Each appender writes only records at or above its own threshold, in its own format.
- Keep the caller safe. An appender that throws is counted and skipped, and the other appenders still get the record.
- Write slow destinations on a background thread through a bounded queue. When the queue is full, the new record is dropped and counted.
- Close in order: refuse new records, write every accepted one, then close each appender once.
Out of scope, and we come back to these: rolling files by size or day, reading levels from a configuration file, structured fields, and per-request context such as a request id.
Everything lives in memory in one process. The code must also handle:
- Concurrency. Every request thread logs into the same appenders, and a level change can happen while they do.
- Rules that change. Formats and destinations differ between services and change over time.
- Testability. Tests need a fixed clock and an appender they can read back.
Finding the classes
The nouns in the questions above are logger, logger names, level, log event, destination, console, file, background writing and layout. Some become classes; some are dropped.
Should code make loggers with new, or ask for them by name?
Each class makes its own Logger with new
This is simple, and each class holds its own object. But there is then no single "app.payments" logger to switch to DEBUG. Every class that logs under that name holds a different object with its own level, and none of them knows its parent.
Ask LogManager for them by name; one logger per nameOur pick
LogManager.getLogger("app.payments") returns the same object every time, makes its parents on the way, and links each logger to its parent. A level set on app.payments reaches every class that logs under that name or below it. The cost is a lookup in a map the first time a class asks for its logger.
Data or behaviour?
A LogRecord is data: it is created once and never changes, so it is a Java record. Level is a fixed, ordered set, so it is an enum. The behaviour lives in Logger, LogManager and the appenders.
The class diagram
The classes fall into three groups:
- Data:
Levelis an enum andLogRecordis a record, with no behaviour beyond comparing levels. - The core:
LogManagerandLogger. They hold the tree of names and levels, and send each record to the right appenders. - Rules and destinations:
AppenderandFormatter, and the classes that implement them. These change from one service to the next, so the core only ever sees the interfaces.
Building it
Levels and records
A level is a position in an ordered list. isAtLeast compares two of them, and that one comparison drives both the logger's check and each appender's threshold.
public enum Level { TRACE, DEBUG, INFO, WARN, ERROR, OFF; /** True if this level is the same as or more serious than {@code other}. */ public boolean isAtLeast(Level other) { return compareTo(other) >= 0; }OFF sits above ERROR. A logger set to OFF writes nothing at all, and a call that tries to log at OFF is refused with an IllegalArgumentException, because that can only be a programmer's mistake.
A record holds everything an appender needs. It is made once per log call that passes the check, and every appender gets the same object.
public record LogRecord(Instant time, Level level, String loggerName, String threadName, String message, Throwable error) { public LogRecord { Objects.requireNonNull(time, "time"); Objects.requireNonNull(level, "level"); Objects.requireNonNull(loggerName, "loggerName"); Objects.requireNonNull(threadName, "threadName"); Objects.requireNonNull(message, "message"); if (level == Level.OFF) { throw new IllegalArgumentException("nothing is logged at OFF"); } }When are a record's time and thread taken?
When an appender writes the record
Each appender reads the clock and the current thread when it writes. That works for an appender that writes at once, but a background writer writes later, on its own thread. Every line it writes would carry the writer's thread name and the time it caught up, not when or where the event happened.
At the call, on the caller's threadOur pick
LogManager reads the clock and Thread.currentThread().getName() when it builds the record, before any appender sees it. A record written a second later by a background thread still says when and where it happened. The cost is one clock read per enabled call, even if every appender then skips the record.
The clock comes from the constructor, as a java.time.Clock. The demo and the tests pass a clock that moves only when told to, so the times in the output are the same on every run. If the clock throws or returns null, LogManager gives the record the latest good time it has seen, or 1970-01-01T00:00:00Z if there has been none. It counts the failure in clockFailures, so a broken clock cannot fail the caller either.
Loggers and their names
getLogger turns a dotted name into a logger, making its parents first.
public Logger getLogger(String name) { Objects.requireNonNull(name, "name"); Logger found = loggers.get(name); if (found != null) { return found; } if (name.length() > MAX_NAME_LENGTH || !NAME.matcher(name).matches()) { throw new IllegalArgumentException("not a logger name: \"" + name + "\""); } int dot = name.lastIndexOf('.'); Logger parent = dot < 0 ? root : getLogger(name.substring(0, dot)); return loggers.computeIfAbsent(name, n -> new Logger(n, parent, null, this)); }Line 67 asks for the parent before the child exists. app.payments.upi asks for app.payments, which asks for app, so app is made first and each logger is linked to the one above it. Line 68 uses computeIfAbsent, so two threads asking for a new name at once get the same object. The parent is worked out before computeIfAbsent, because a ConcurrentHashMap refuses a mapping function that changes the same map. A name is made of dot-separated parts of letters, digits, _, $ and -, so a nested class name such as com.shop.Outer$Inner works. A name longer than 200 characters, or with an empty part such as app..x, is refused with an IllegalArgumentException.
A logger keeps a level of its own, or none. The level that decides is the logger's own level if it has one, or else the nearest parent's.
private volatile Level level; public void setLevel(Level level) { if (level == null && parent == null) { throw new IllegalArgumentException("the root logger needs a level"); } this.level = level; } /** The level that decides: this logger's own, or the nearest parent's. */ public Level effectiveLevel() { Logger logger = this; while (true) { Level set = logger.level; if (set != null) { return set; } logger = logger.parent; } }Walk up to the nearest level on every call, or keep the answer in each logger?
Keep each logger's effective level in a field, and update the children when a level changes
The check is then one field read. But a level change on app has to find and update every logger below it, while other threads read those fields. Getting that right needs a lock or a version number across the whole tree, and a logger made during the change can miss it.
Walk up on every callOur pick
effectiveLevel reads the level field of each logger up to the first one that has a level. A change on app is seen by every logger below it on their next call, with nothing to update. The cost is one field read per level of nesting on every call: at most four reads for a name like app.payments.upi.
How does a level change reach the other threads?
A plain field
Writing a plain field is cheapest, but Java does not promise that another thread ever sees the new value. A request thread could keep reading the old level from its own cache.
A lock around every read and write of the level
This is correct, but every log call from every thread would take the same lock just to read a level, and logging runs on the hottest paths in the service.
A volatile field on each loggerOur pick
level is volatile (line 20), so a change made by one thread is seen by every other thread on its next read, with no lock. The cost is that a level and an appender changed together are two separate writes: another thread can see one before the other.
A check before any work
Every log method checks the level first. Only a call that passes reaches LogManager.
public void log(Level level, String message, Throwable error) { if (enabledFor(level)) { manager.dispatch(this, level, () -> message, error); } } /** The message is built only if the level is enabled. */ public void log(Level level, Supplier<String> message) { Objects.requireNonNull(message, "message"); if (enabledFor(level)) { manager.dispatch(this, level, message, null); } } private boolean enabledFor(Level level) { Objects.requireNonNull(level, "level"); if (level == Level.OFF) { throw new IllegalArgumentException("nothing is logged at OFF"); } return level.isAtLeast(effectiveLevel()); }Should a message that is not logged cost anything?
Take only a String
A call like debug("cart: " + cart) builds the string before the logger can check its level. On a hot path at INFO, every disabled debug line still pays for the concatenation and for cart.toString().
Ask callers to check first, with if (logger.isEnabled(DEBUG))
This works, and isEnabled is there for it. But every call site needs the extra lines, and a caller who forgets pays the full cost without noticing.
Offer a Supplier, built only after the level checkOur pick
debug(() -> "cart: " + cart) passes a lambda instead of a string. The logger checks the level first (line 89), and the lambda runs only if the check passes. A disabled line costs the check and, when the lambda captures a variable, one small object. The String versions stay for messages that cost nothing to build.
From a call to the appenders
dispatch builds the record and offers it to the appenders on the logger and on every logger above it.
void dispatch(Logger source, Level level, Supplier<String> message, Throwable error) { if (closed.get()) { afterClose.incrementAndGet(); return; } if (dispatching.get() || writerThreads.contains(Thread.currentThread())) { // A log call made from inside an appender, on the caller's thread or on a // writer thread. Writing it could loop for ever, so it is counted and dropped. nestedCalls.incrementAndGet(); return; } dispatching.set(true); try { LogRecord record = new LogRecord(now(), level, source.name(), Thread.currentThread().getName(), textOf(message), error); for (Logger logger = source; logger != null; logger = logger.parent()) { for (Appender appender : logger.appenders()) { appendQuietly(appender, record); } } } finally { dispatching.remove(); } }The loop on line 104 walks from the logger to the root, the same path as the level check. An appender on app hears from app.orders and app.payments.upi alike, so one console appender on the root covers the whole service. One appender added to both a logger and its parent writes each record twice, once for each logger.
Lines 90 to 93 drop every call that starts after LogManager.close, and count it in afterClose. A call already past that check can still reach an appender as it closes; an AsyncAppender then refuses the record and counts it in refused.
Lines 94 to 99 handle an appender that logs. If an appender calls a logger while it writes, dispatch would call the same appender again, and again, until the stack runs out. The dispatching flag is set for this thread while its record is being written, so a log call made from inside an appender is counted and dropped. The flag is cleared in a finally, so the next ordinary call on that thread is not dropped. A message Supplier runs inside the flag too, so a message that logs while it is built is dropped the same way.
The flag is per thread, so it cannot see an appender that sits behind an AsyncAppender and logs on the writer thread. That loop would go round the queue for ever. LogManager.writerThreads(name) is a thread factory for AsyncAppender, and it lists each thread it makes in writerThreads. A log call on one of those threads is dropped and counted the same way. An AsyncAppender made with some other thread factory gets no such guard. The factory is for AsyncAppender only: every log call on a thread it makes is dropped, so giving it to a thread pool would silence that pool.
Each appender is called through appendQuietly.
private void appendQuietly(Appender appender, LogRecord record) { try { if (record.level().isAtLeast(appender.threshold())) { appender.append(record); } } catch (RuntimeException e) { // A broken appender must not break the caller's code or the appenders after it. appenderFailures.incrementAndGet(); } }What happens when an appender throws?
Let the exception reach the caller
The caller learns at once that logging failed. But a full disk would then fail a payment that had nothing to do with the disk, and the appenders after the broken one would never see the record.
Log the failure through the same logger
This keeps the failure visible in the log, but the broken appender is part of that log. Writing the failure calls it again, which fails again.
Count it, and carry on with the next appenderOur pick
appendQuietly catches the RuntimeException, adds one to appenderFailures, and the loop goes on. The caller's code never sees it, and the other appenders still get the record. The cost is that the failure is only a number: something has to read appenderFailures() and alert on it. An Error, such as running out of memory, is not caught and goes on to the caller.
A Supplier that throws gets the same care. textOf catches it, counts it in messageFailures, and the record is still written with the text "[the message could not be built: …]", so the line is not silently missing.
Appenders and formats
An appender is anything that takes a record. It has a threshold, and it may need flushing and closing.
public interface Appender extends AutoCloseable { /** The least serious level this appender writes. */ Level threshold(); void append(LogRecord record); /** Waits until everything already appended has been written. */ default void flush() { } /** Flushes, then lets go of whatever the appender holds. */ @Override default void close() { flush(); }}How a record looks is a separate question from where it goes. The console wants one readable line, and the alerting system wants JSON.
TextFormatter writes the line, then the exception and each of its causes.
public String format(LogRecord record) { StringBuilder text = new StringBuilder() .append(record.time()).append(' ') .append(String.format("%-5s", record.level())).append(' ') .append('[').append(record.threadName()).append("] ") .append(record.loggerName().isEmpty() ? "root" : record.loggerName()) .append(" - ").append(record.message()).append('\n'); // A cause chain can loop back on itself, so each exception is written once. Set<Throwable> seen = Collections.newSetFromMap(new IdentityHashMap<>()); String prefix = " "; for (Throwable error = record.error(); error != null && seen.add(error); error = error.getCause()) { text.append(prefix).append(error).append('\n'); for (StackTraceElement frame : error.getStackTrace()) { text.append(" at ").append(frame).append('\n'); } prefix = " Caused by: "; } return text.toString();Lines 20 to 22 guard against a cause chain that loops back on itself, which Java allows through initCause. Without the seen set, the loop on line 22 would never end. JsonFormatter escapes quotes, backslashes and control characters, so a message with a line break in it still comes out as one line of JSON.
StreamAppender writes to a PrintStream: System.out, or a file the application opened.
@Override public void append(LogRecord record) { String text = formatter.format(record); // One print per record. PrintStream holds its own lock for the whole call, // so another thread's record cannot land between the lines of this one. out.print(text); }How are a record's lines kept together?
Write each line as it is formatted
The record line, then each stack frame, is printed as soon as it is ready. When two threads log errors at once, their frames interleave, and the log shows one exception's frames under another thread's message.
A lock in each appender around all of its writes
This keeps a record whole, but the appender then holds its own lock while it formats, and every thread waits for that work as well as for the write.
Build the whole text, then write it in one callOur pick
The formatter returns the whole record, stack frames included, as one string (line 28), and the appender prints it with one call (line 31). PrintStream holds its own lock for the length of one print, so another thread's record cannot land inside it. Formatting happens before that lock, on the caller's thread. The cost is one string per record that holds every line, which for a deep stack trace is a few kilobytes.
PrintStream never throws on a failed write; it sets an error flag that checkError() reports. A full disk behind a StreamAppender therefore loses lines without a count. A file appender that must notice that would check the flag after each write and count it as a failure.
Writing on another thread
A slow destination, such as a file on a busy disk or a store across the network, would make every request thread wait on each write. AsyncAppender puts the record on a queue and returns, and one background thread does the writing.
@Override public void append(LogRecord record) { Objects.requireNonNull(record, "record"); // Many appends share the read lock; close takes the write lock, so no record // can be added after close has decided the queue is finished. gate.readLock().lock(); try { if (closed || writerDone) { refused.incrementAndGet(); return; } if (queue.offer(record)) { accepted.incrementAndGet(); } else { dropped.incrementAndGet(); } } finally { gate.readLock().unlock(); } }The queue is an ArrayBlockingQueue with a fixed capacity. offer on line 70 never waits: it adds the record if there is room and returns false if not.
When the queue is full, wait or drop?
Wait for room, with put
No record is ever lost. But when the disk stalls, the queue fills, and then every request thread that logs waits for the disk. A logging problem becomes an outage of the whole service.
Drop the oldest record to make room
The newest lines, often the most useful, are kept. But taking the oldest record off the queue races with the writer thread, and a caller has to change the queue instead of only adding to it.
Drop the new record and count itOur pick
offer fails, dropped goes up by one, and the caller carries on at once. The records already queued stay in order. The cost is lost lines while the destination is stalled, and dropped() is how anyone finds out. Writing a line that says how many were dropped is a follow-up.
The writer thread takes records off the queue one at a time.
private void drain() { LogRecord inHand = null; try { while (true) { try { inHand = queue.take(); } catch (InterruptedException e) { // Only close stops the writer, so an interrupt is ignored. continue; } if (inHand == STOP) { inHand = null; return; } try { target.append(inHand); } catch (RuntimeException e) { failures.incrementAndGet(); } inHand = null; synchronized (progress) { handled++; progress.notifyAll(); } } } finally { // Under the write lock, so no append can be accepted after this. gate.writeLock().lock(); try { writerDone = true; lost.addAndGet(queue.size() + (inHand != null ? 1 : 0)); } finally { gate.writeLock().unlock(); } synchronized (progress) { progress.notifyAll(); } } }A record the wrapped appender throws on is counted in failures, and the writer goes on to the next one. After each record, handled goes up under the progress lock and waiting threads are woken. flush uses that. It takes the write lock for a moment to read accepted, which waits for any append still inside, then waits until handled reaches that number. If the writer dies, for example from an Error, the finally sets writerDone, so flush and close return instead of waiting for ever. The records still on the queue, and the one it was writing, are then lost, and the finally counts them in lost. It sets writerDone under the write lock, so no append can be accepted after that point. From then on append refuses every record and counts it in refused, and writerAlive() returns false, so a health check can notice.
Closing without losing a record
close has to stop the writer without stranding a record that a caller has already been told was accepted.
/** * Refuses new records, writes every accepted one, stops the writer, closes the target. * A second call waits until the first has finished. */ @Override public void close() { if (Thread.currentThread() == writer) { throw new IllegalStateException("close was called from the writer thread"); } boolean first; gate.writeLock().lock(); try { first = !closed; if (first) { closingThread = Thread.currentThread(); } closed = true; } finally { gate.writeLock().unlock(); } if (!first) { // A close nested inside the first one, on the same thread, cannot wait for it. if (Thread.currentThread() != closingThread) { awaitUninterruptibly(closeDone); } return; } try { // No append can add a record now, so STOP is the last thing on the queue. sendStop(); joinUninterruptibly(writer); target.close(); } finally { closeDone.countDown(); } }STOP is a record that only this class can make. When the writer takes it off the queue, it knows nothing comes after it. That is true only if no append can add a record behind STOP.
How does close know that no record is still on its way in?
A volatile closed flag
append reads the flag, then offers the record. Between those two steps, close can set the flag and put STOP on the queue. The record then lands behind STOP, append counts it as accepted, and the writer stops before it gets there.
One lock around every append and close
This is correct and simple. Offers already take turns on the ArrayBlockingQueue's own lock, so the extra lock costs less than it looks. Its cost is that each append also waits for the others to finish their closed check, which nothing here needs.
A read-write lock: appends share it, close takes it aloneOur pick
Close must keep appends out, but appends do not need to keep each other out at this layer. append holds the read lock from the closed check to the end of the offer (lines 64 to 76), and many threads can hold it at once. close takes the write lock (line 118), which waits for every append already inside and keeps new ones out until closed is set. After that, every append sees closed and is refused, so STOP is the last record on the queue. The cost is a read lock taken and released on every append, even though close happens once.
close then puts STOP on the queue, waiting for room if the queue is full, and joins the writer thread. The wrapped appender is closed last, after its final record is written. A second call to close sees closed already set and waits on closeDone until the first close has finished, so it never returns while records are still being written. The one exception is a close nested inside the first on the same thread, for example from the wrapped appender's own close. It returns at once, because it cannot wait for itself. A call to close from the writer thread itself, for example from the wrapped appender, would wait for itself, so it is refused with an IllegalStateException. flush from the writer thread returns at once for the same reason. LogManager.close runs once; a second call does nothing. It closes every appender once, using an identity set, and closes the AsyncAppenders first, so their queues are written before anything else closes. An appender that is wrapped by an AsyncAppender and also attached to a logger directly is still closed twice. It should be attached only through the wrapper.
The writer is a daemon thread, so it does not keep the JVM alive. A service that exits without calling LogManager.close loses whatever is still queued.
Many threads at once
The locks all sit in the appenders and the queue. MemoryAppender adds each formatted record to its list under its own lock. AsyncAppender uses the read-write lock above to keep close and append apart, and its progress lock guards the count that flush waits on. ArrayBlockingQueue has a lock of its own inside, and PrintStream holds one for each print. Loggers and LogManager take no lock of their own. The appender list is a CopyOnWriteArrayList, which gives each record a snapshot of the list, and the level is volatile.
@Override public void append(LogRecord record) { String text = formatter.format(record); synchronized (lock) { written.add(text); } }The format runs before the lock (line 29), so threads wait for each other only to add a string to the list.
RaceCheck checks both. The first part has 8 threads log 2,000 records each into one shared appender and checks that every record arrived once, in each thread's order. The second closes an async appender while 4 threads are still appending to it, 300 times, and checks that every accepted record was written.
One shared appender, 8 threads, 16000 records: every record written exactly once: yes each thread's records in order: yes no logging thread crashed: yes Closing while 4 threads log, 300 rounds: every accepted record was written: yes accepted + dropped + refused = attempted: yes no logging thread crashed: yes
With the lock removed from MemoryAppender, the first part lost thousands of the 16,000 records, and in some runs the list was so damaged that reading it back threw a NullPointerException. With the read-write lock replaced by a volatile flag, most runs had a few rounds where an accepted record was never written. That failure is rare, which is why it is easy to ship without noticing.
The final design
LogManager is the core. It owns one Logger per name and builds every record, and it reaches destinations and layouts only through two interfaces: each Logger holds Appender objects, and the appenders hold a Formatter. A new destination or layout is a new class, and LogManager and Logger do not change. Logger and LogManager take no lock of their own, so a log call takes none until its record reaches an appender or a queue.
| S.No. | The question | What we chose | Why |
|---|---|---|---|
| 1 | Should code make loggers with new, or ask for them by name? | Ask LogManager for them by name; one logger per name | A level set on a name reaches every class that logs under it |
| 2 | When are a record's time and thread taken? | At the call, on the caller's thread | A record written later on another thread still says when and where it happened |
| 3 | Walk up to the nearest level on every call, or keep the answer in each logger? | Walk up on every call | A level change needs no update to the loggers below it |
| 4 | How does a level change reach the other threads? | A volatile field on each logger | Every thread sees the change on its next call, with no lock |
| 5 | Should a message that is not logged cost anything? | Offer a Supplier, built only after the level check | A disabled line costs the check and little else |
| 6 | What happens when an appender throws? | Count it, and carry on with the next appender | A broken log never breaks the caller or the other appenders |
| 7 | How are a record's lines kept together? | Build the whole text, then write it in one call | Another thread's record cannot land between a record's lines |
| 8 | When the queue is full, wait or drop? | Drop the new record and count it | A stalled disk never holds up a request thread |
| 9 | How does close know that no record is still on its way in? | A read-write lock: appends share it, close takes it alone | No record can be queued behind STOP |
Here is the debug line from the overview, end to end:
- The caller runs
upi.debug(() -> "collect request sent for ORD-7").Logger.logcallsenabledFor, which walks up fromapp.payments.upitoapp.paymentsand finds DEBUG, so the check passes. No lock is taken. LogManager.dispatchsets thedispatchingflag for this thread, reads the clock and the thread name, runs theSupplier, and builds oneLogRecord.- The loop goes from
app.payments.upiup to the root, andappendQuietlyoffers the record to each appender in turn. Onapp.payments, the JSON alerts skip it on their WARN threshold, and theAsyncAppendertakes it. AsyncAppender.appendtakes the read lock, sees the appender is open, andoffers the record to the queue. It releases the lock and returns. The loop goes on to the root, where the console skips the record on its INFO threshold, and thendispatchclears the flag. The caller has not waited for any write.- The writer thread takes the record off the queue and calls
MemoryAppender.append, the demo's stand-in for the slow store. That formats the record and adds it to the list under its own lock. This is the outside call, and it runs on the writer's thread, not the caller's.
The complete code
The browser below has the whole project. Click a class name in any file to open it, or use Find to search every file.
package log; import appender.Appender;import appender.AsyncAppender;import java.time.Clock;import java.time.Instant;import java.util.Collections;import java.util.IdentityHashMap;import java.util.Objects;import java.util.Set;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.ConcurrentMap;import java.util.concurrent.ThreadFactory;import java.util.concurrent.atomic.AtomicBoolean;import java.util.concurrent.atomic.AtomicLong;import java.util.concurrent.atomic.AtomicReference;import java.util.function.Supplier;import java.util.regex.Pattern; /** * Hands out one Logger per name, and sends each record from a logger to the appenders * on it and on every logger above it. The application makes one LogManager at startup * and passes it to the code that needs it; nothing here is static. */public final class LogManager implements AutoCloseable { public static final int MAX_NAME_LENGTH = 200; private static final Pattern NAME = Pattern.compile("[A-Za-z0-9_$-]+(\\.[A-Za-z0-9_$-]+)*"); private final Clock clock; private final Logger root; private final ConcurrentMap<String, Logger> loggers = new ConcurrentHashMap<>(); private final ThreadLocal<Boolean> dispatching = ThreadLocal.withInitial(() -> false); private final Set<Thread> writerThreads = ConcurrentHashMap.newKeySet(); private final AtomicReference<Instant> lastTime = new AtomicReference<>(Instant.EPOCH); private final AtomicBoolean closed = new AtomicBoolean(); private final AtomicLong appenderFailures = new AtomicLong(); private final AtomicLong messageFailures = new AtomicLong(); private final AtomicLong nestedCalls = new AtomicLong(); private final AtomicLong clockFailures = new AtomicLong(); private final AtomicLong afterClose = new AtomicLong(); public LogManager(Clock clock, Level rootLevel) { this.clock = Objects.requireNonNull(clock, "clock"); Objects.requireNonNull(rootLevel, "rootLevel"); this.root = new Logger("", null, rootLevel, this); loggers.put("", root); } public Logger root() { return root; } /** * The logger for a dotted name such as "app.payments", made the first time it is * asked for, together with its parents. The same name always gives the same object. */ public Logger getLogger(String name) { Objects.requireNonNull(name, "name"); Logger found = loggers.get(name); if (found != null) { return found; } if (name.length() > MAX_NAME_LENGTH || !NAME.matcher(name).matches()) { throw new IllegalArgumentException("not a logger name: \"" + name + "\""); } int dot = name.lastIndexOf('.'); Logger parent = dot < 0 ? root : getLogger(name.substring(0, dot)); return loggers.computeIfAbsent(name, n -> new Logger(n, parent, null, this)); } /** * A thread factory for AsyncAppender only. Log calls made on the threads it makes, such * as an appender behind the queue that logs, are dropped instead of looping for ever. * Every log call on those threads is dropped, so do not give it to a thread pool. */ public ThreadFactory writerThreads(String name) { Objects.requireNonNull(name, "name"); return task -> new Thread(() -> { writerThreads.add(Thread.currentThread()); try { task.run(); } finally { writerThreads.remove(Thread.currentThread()); } }, name); } /** Called by a logger once its level check has passed. */ void dispatch(Logger source, Level level, Supplier<String> message, Throwable error) { if (closed.get()) { afterClose.incrementAndGet(); return; } if (dispatching.get() || writerThreads.contains(Thread.currentThread())) { // A log call made from inside an appender, on the caller's thread or on a // writer thread. Writing it could loop for ever, so it is counted and dropped. nestedCalls.incrementAndGet(); return; } dispatching.set(true); try { LogRecord record = new LogRecord(now(), level, source.name(), Thread.currentThread().getName(), textOf(message), error); for (Logger logger = source; logger != null; logger = logger.parent()) { for (Appender appender : logger.appenders()) { appendQuietly(appender, record); } } } finally { dispatching.remove(); } } /** Waits until every appender has written what it was given. */ public void flush() { for (Appender appender : allAppenders()) { try { appender.flush(); } catch (RuntimeException e) { appenderFailures.incrementAndGet(); } } } /** * Refuses new calls, then closes every appender once: the async ones first, so their * queues are written before anything else closes. A second call does nothing. */ @Override public void close() { if (!closed.compareAndSet(false, true)) { return; } Set<Appender> all = allAppenders(); for (boolean asyncPass : new boolean[] {true, false}) { for (Appender appender : all) { if ((appender instanceof AsyncAppender) == asyncPass) { closeQuietly(appender); } } } } private void closeQuietly(Appender appender) { try { appender.close(); } catch (RuntimeException e) { appenderFailures.incrementAndGet(); } } /** Appenders that threw while writing, flushing or closing. */ public long appenderFailures() { return appenderFailures.get(); } /** Messages whose Supplier threw; each was still logged, with a placeholder text. */ public long messageFailures() { return messageFailures.get(); } /** Times the clock threw or gave null; the record got the latest good time instead. */ public long clockFailures() { return clockFailures.get(); } /** Log calls made after close, which were dropped. */ public long afterClose() { return afterClose.get(); } /** Log calls made from inside an appender, which were dropped. */ public long nestedCalls() { return nestedCalls.get(); } private void appendQuietly(Appender appender, LogRecord record) { try { if (record.level().isAtLeast(appender.threshold())) { appender.append(record); } } catch (RuntimeException e) { // A broken appender must not break the caller's code or the appenders after it. appenderFailures.incrementAndGet(); } } private Instant now() { try { Instant time = clock.instant(); if (time != null) { lastTime.accumulateAndGet(time, (a, b) -> a.isAfter(b) ? a : b); return time; } } catch (RuntimeException e) { // Falls through: a broken clock must not stop the log call. } clockFailures.incrementAndGet(); // The latest good time seen, or 1970-01-01T00:00:00Z if there has been none. return lastTime.get(); } private String textOf(Supplier<String> message) { try { return String.valueOf(message.get()); } catch (RuntimeException e) { messageFailures.incrementAndGet(); return "[the message could not be built: " + e + "]"; } } private Set<Appender> allAppenders() { Set<Appender> all = Collections.newSetFromMap(new IdentityHashMap<>()); for (Logger logger : loggers.values()) { all.addAll(logger.appenders()); } return all; }}demo.Main is a morning in a shop's backend, with every requirement and the failure paths:
Levels: app.orders INFO, app.payments.upi DEBUG
1. An order is placed
2026-11-20T09:30:00Z INFO [main] app.orders - order ORD-7 placed for $1,499
2. A debug line on a logger at INFO
The message was built 0 times
3. A debug line under app.payments
The console printed nothing. The slow store has:
2026-11-20T09:30:01Z DEBUG [main] app.payments.upi - collect request sent for ORD-7
4. A payment fails
2026-11-20T09:30:02Z ERROR [main] app.payments - payment failed for ORD-7
java.lang.IllegalStateException: card declined
at demo.Main.declined(Main.java:111)
at demo.Main.main(Main.java:62)
Caused by: java.lang.IllegalArgumentException: bank says: insufficient funds
at demo.Main.declined(Main.java:111)
at demo.Main.main(Main.java:62)
The alerting system got:
{"time":"2026-11-20T09:30:02Z","level":"ERROR","logger":"app.payments","thread":"main","message":"payment failed for ORD-7","error":"java.lang.IllegalStateException: card declined"}
5. An appender whose disk is full
2026-11-20T09:30:02Z INFO [main] app.orders - order ORD-8 placed for $349
Appender failures: 1
6. An appender that logs while it writes
2026-11-20T09:30:02Z INFO [main] app.audit - refund approved for ORD-5
Log calls dropped because they came from inside an appender: 1
7. Debug turned on for all of app, while it runs
app.orders is now DEBUG; the message was built 1 time
8. A stalled disk behind a queue of 3
2026-11-20T09:30:02Z INFO [main] jobs.settlement - batch line 1
2026-11-20T09:30:02Z INFO [main] jobs.settlement - batch line 2
2026-11-20T09:30:02Z INFO [main] jobs.settlement - batch line 3
2026-11-20T09:30:02Z INFO [main] jobs.settlement - batch line 4
2026-11-20T09:30:02Z INFO [main] jobs.settlement - batch line 5
2026-11-20T09:30:02Z INFO [main] jobs.settlement - batch line 6
Accepted 4, dropped 2
Written once the disk recovered: 4
9. Shutting down
Log calls after close: 1, slow store lines: 2, writer threads still running: falseNotice five things in the output:
- Step 2 printed nothing from the logger, and the message was built 0 times. The
Suppliernever ran, becauseapp.orderswas at INFO. - Step 3 printed nothing on the console, but the slow store got the line, with the caller's thread name
maineven though the writer thread wrote it. That is requirement 3 and decision 2. - Step 5 still printed the ORD-8 line on the console, after the broken appender on
app.ordersthrew. The failure was counted once (requirement 4). - Step 8 shows all six batch lines on the console, which writes at once, while the async queue of 3 behind a stalled disk accepted 4 and dropped 2. After the disk recovered, the 4 accepted lines were written (requirement 5).
- Step 9 dropped the warning logged after close, so it reached neither the console nor any queue, and both writer threads had stopped (requirement 6).
Follow-up questions
| The interviewer asks | What changes | What does not |
|---|---|---|
| Roll the log file by size or by day | A new appender class that swaps files when a limit is reached | Logger, LogManager, the formatters and the other appenders |
| Read levels and appenders from a file, and reload it | A loader that calls setLevel, addAppender and removeAppender | Logger, LogManager and every appender |
| Add structured fields, such as an order id, to each record | LogRecord gains a map of fields, Logger gains methods that take them, and each Formatter writes them | LogManager's dispatch loop and the appenders |
| Put a request id on every line a request thread writes | LogManager copies a per-thread context into each record, and LogRecord gains a field for it | Logger's methods, the appenders and the queue |
| Write a line saying how many records were dropped | AsyncAppender, which needs a Clock to stamp that line | Logger, LogManager and the appender it wraps |
| Stop a logger's records from reaching its parents' appenders | Logger gains a flag, and LogManager's loop stops at a logger that has it set | The appenders and the formatters |
| Send ERROR records to a remote alerting service | A new appender, placed behind an AsyncAppender so a slow network never holds the caller | Everything else |
Close with a deadline, because a hung destination makes close and flush wait for ever | AsyncAppender.close(timeout), which stops waiting at the deadline and counts what was left on the queue | Logger, LogManager and the wrapped appender |
| Keep only 1 in 100 DEBUG lines | A sampling appender that wraps another appender, like AsyncAppender does | Logger, LogManager and the wrapped appender |
When the interviewer asks one of these, say which classes change and which do not before writing any code. Most of these land in a new appender or a new formatter, which is what the two interfaces are for. Structured fields and per-request context change LogRecord, and every formatter has to learn to print the new field.
What the interviewer looks for
Mid-level
A mid-level candidate shows a Logger with levels, an appender interface with a console and a file appender, and a check that skips disabled levels. Their logger writes the right lines in a single-threaded demo.
Senior
A senior candidate adds named loggers with inherited levels, takes the time and thread at the call, and makes a disabled line cheap with a Supplier. They catch appender failures so a broken log cannot fail a request, and they keep a record's lines together under many threads.
Staff+
A staff candidate treats logging as code that runs inside everything else. They put slow appenders behind a bounded queue and say what happens when it is full, they close it without losing an accepted record, and they guard against an appender that logs. They also say which costs they accepted: lost lines while a disk stalls, a failure count someone must watch, and a writer thread that can die.
Common mistakes
- Building the message before the check.
debug("cart: " + cart)pays for the string even when DEBUG is off. ASupplieror anisEnabledcheck avoids it. - Letting an appender's exception reach the caller. A full log disk then fails payments. Catch it, count it, and move on to the next appender.
- Printing a stack trace one line at a time. Two threads logging errors at once interleave their frames. Build the whole text, then write it once.
- Blocking the caller on a full queue. A stalled disk then stops every request thread. Drop and count, or at least make blocking a choice the caller can see.
- Closing with a flag and no lock. A record accepted just before close can land behind the stop marker and never be written.
- Taking the time and thread in the background writer. Every line then shows the writer's thread and the time it caught up, not when the event happened.
- Attaching one appender to a logger and to its parent. Each record from that logger is then written twice, because the record goes up the tree to both.
Summary
LogManagerhands out oneLoggerper dotted name, and a logger with no level uses the nearest parent's.- A level check comes first, and a
Suppliermessage is built only if it passes, so a disabled line costs almost nothing. - Each record is built once, with the time and thread taken at the call, and offered to every appender up the logger tree.
- An appender that throws is counted and skipped, and a log call from inside an appender is dropped, so logging never breaks or loops the caller.
- Appenders are Observers of their logger,
Formatteris a Strategy andAsyncAppenderis a Decorator, so new destinations, layouts and slow stores need no change to the core. - The async appender drops new records when its queue is full and counts them, and its read-write lock lets
closewrite every record it accepted. - Loggers and
LogManagertake no lock of their own; they rely onvolatilefields and a copy-on-write appender list, and the locks sit in the appenders and the queue.