Designing a Logging Framework

Difficulty: Beginner Patterns: Chain of Responsibility, Decorator, Singleton Asked at: Amazon, Flipkart, Microsoft, PhonePe


Every service has one. A caller writes log.info("order placed") and the line shows up on the console in development, in a rotated file in production, and as JSON in a log aggregator at scale. The parts are small – a level, a record, a destination – which is why this turns up as a beginner machine-coding problem. Writing to a file is not what is being graded.

Two things are. The first is that this one problem contains two different chains, and conflating them is the bug. The logger hierarchy is a first-match walk: a registry resolving com.shop.orders climbs to com.shop, then com, then the root, stopping at the first name with an explicitly configured level, which is what lets one config line turn on debug for a whole subtree. The appender list is the opposite shape – a pipeline where every destination that passes its own threshold gets the record and nobody short-circuits. Give appenders a next pointer and return after the first successful write and you have silently built a logger where adding a console appender deletes your audit file. Riding alongside that is a detail that costs one line and is skipped constantly: isLoggable(level) has to be checked before the message is built, because log.debug("cart=" + cart) concatenates the string, walks the cart and allocates the garbage even when debug is off.

The second is that async logging is where a logger stops being harmless and becomes a liability. Writing to disk or over the network on the caller’s thread puts I/O latency directly into business code, so the record goes onto a bounded queue and a background thread drains it. That handoff forces a decision nobody can dodge: what happens when the queue is full? Block the application, drop the newest record, or drop the oldest. Blocking means your logger can take down the service it was meant to observe. Dropping means the one incident you are debugging is the one with the missing logs. There is no option that costs nothing, and an answer of “the queue will not fill” is the wrong answer.

The trap, in one sentence: candidates build the class hierarchy – Logger, Appender, Formatter – hand it in, and never say what the level check costs, which chain is which, or what the framework throws away when the disk falls behind.

💡 Appender = one destination a record can be written to – console, file, socket, an in-memory list in a test. The name comes from log4j and it is the single most useful abstraction in the design, because every new destination is then a new class rather than an edit.

💡 Effective level = the threshold that actually applies to a logger after inheritance is resolved. com.shop.orders may have no level of its own and still be at DEBUG because com.shop is, which is the whole point of naming loggers after packages. Learn more →

💡 Backpressure = what a system does when work arrives faster than it can be finished. A bounded queue plus a stated overflow policy is backpressure made explicit; an unbounded queue is backpressure hidden until the heap fills. Learn more →


Functional Requirements

  1. Levels – TRACE, DEBUG, INFO, WARN, ERROR, compared by severity, with OFF available to silence a subtree entirely.
  2. Named loggers in a hierarchy – getLogger("com.shop.orders") inherits its level from the nearest configured ancestor, so configuring a parent configures every child.
  3. Multiple appenders – one record fans out to console, file and remote destinations, each with its own threshold and its own formatter.
  4. Pluggable formatting – the same record renders as a human-readable line or as JSON, chosen per appender.
  5. Asynchronous writing – a log call hands the record off and returns; formatting and I/O happen on a writer thread.
  6. A declared overflow policy – when the queue is full the framework blocks, drops the newest or drops the oldest, by configuration, and counts whatever it discarded.
  7. Flush on shutdown – close() drains the backlog before the process exits, because a buffered logger that loses its last two thousand records loses the crash.

Non-Functional Requirements

  1. No I/O on the caller’s thread – the hot path is one level check and one bounded-queue offer, with no disk or socket syscall between log.info(...) and the return.
  2. O(1) steady-state level check – hierarchy resolution is O(depth) the first time and then cached, so the recurring cost is one ConcurrentHashMap lookup plus an int comparison.
  3. Thread-safe and line-atomic – any number of threads may share a Logger, and one record must produce one undivided line per appender rather than two half-lines interleaved.
  4. Bounded memory, visible loss – the queue has a fixed capacity so a slow disk cannot grow the heap, and every dropped record is counted so the gap in the file is explainable.

Core Entities

Entity Description
LogLevel Enum carrying a numeric severity, so thresholds compare with >=
LogRecord Immutable snapshot of one event: timestamp, level, logger name, message, thread name, optional throwable
LogFormatter Strategy interface turning a record into a string; PatternFormatter emits a human-readable line, JsonFormatter one object per record
Appender A destination, with its own level threshold and formatter
ConsoleAppender / FileAppender The two concrete destinations: stdout with WARN and above split to stderr, and a buffered writer flushed on every ERROR
BufferedAppender Decorator that batches records and forwards them in groups
AsyncAppender Decorator owning a bounded queue and a writer thread; implements the overflow policy
Logger What callers hold: the isLoggable guard, the lambda overload, and the fan-out
LoggerRegistry Interns loggers by name, resolves effective levels, owns the appender list

💡 Immutable = every field is final and set once in the constructor, so the object cannot change after it is handed to another thread. It is what makes passing a LogRecord across a queue safe without a single lock. Learn more →

💡 Decorator = a class that implements the same interface as the object it holds and forwards every call, adding behavior on the way through. AsyncAppender is an Appender that holds an Appender, which is why it can wrap a file, a socket or another decorator without any of them knowing. Learn more →


Two chains, one guard, and the question of what to drop

Start with the version that gets written first. One Logger class holds a level and a list of appenders; log(level, message) compares the level, loops the list and writes. It runs, and then three separate things go wrong.

The first chain: resolving a level by walking names. A service has four hundred classes and therefore four hundred logger names. If each logger stores its own level, configuration is four hundred entries, and “turn on debug for everything under com.shop.orders” is a find-and-replace. The fix is to treat the dotted name as a tree. LoggerRegistry stores only the levels someone explicitly configured, and resolution climbs: com.shop.orders, then com.shop, then com, then the root, returning the first level it finds. The root always has a configured level, which is what terminates the walk – an unterminated chain here would return null and crash on the first log call. This is a first-match walk: exactly one link answers, and nothing below it is consulted.

The second chain: the record’s own path, which is a pipeline. Once the level passes, the record goes to every appender, and each appender applies its own threshold – console at INFO, file at DEBUG, remote at WARN. No appender consumes the record. No appender can stop the others. This matters more than it sounds: if the walk short-circuited, reordering a config file would quietly delete a destination, and the symptom would be “the audit log is missing entries since Tuesday”. The Chain of Responsibility lesson splits chains into exactly these two shapes and files the logging level chain under pipeline rather than first-match, which is the right call for the path a record travels. The lesson also makes the honest admission worth repeating here: a pipeline chain is a Decorator with the field renamed. AsyncAppender and BufferedAppender implement Appender, hold an Appender, and always forward. The only difference from the fan-out list is arity – one delegate instead of several.

So: configuration resolves by first match, records travel by pipeline. Candidates who blur the two produce one of two bugs. Either appenders get a next pointer and a return after the first write, and destinations disappear, or level inheritance becomes additive and the same line is emitted once per ancestor.

The guard, and why it is not optional. Java evaluates arguments before the call. So this:

log.debug("cart=" + cart + " total=" + cart.total())

builds the concatenation, calls toString() on the cart, walks its line items and computes a total – and then enters debug, which discovers the level is INFO and discards all of it. On a request path that runs ten thousand times a second, that is the single most expensive thing a logging framework does to a service, and it does it to produce nothing. Three fixes, in order of how much they ask of the caller:

  • if (log.isLoggable(DEBUG)) log.debug("cart=" + cart) – works everywhere, clutters the call site, and gets forgotten.
  • log.debug(() -> "cart=" + cart) – a Supplier overload, so the framework calls get() only after the guard passes. One lambda allocation when the level is off, no string work.
  • log.debug("cart={} total={}", cart, total) – parameterized placeholders, which is the slf4j answer: the varargs array is allocated but no formatting runs, and the format only happens inside the appender.

All three exist because the guard has to run before the message exists. The design below puts the check at the top of Logger.log, which handles every overload uniformly, and exposes isLoggable publicly for the call sites that need it.

The queue, and the question nobody can dodge. A FileAppender writing on the caller’s thread means a write plus an occasional flush inside business code, and a slow or full disk shows up as p99 latency on checkout. Moving the write behind a BlockingQueue with a dedicated writer thread fixes that and buys a second benefit: formatting – building the pattern string, serialising JSON, rendering a stack trace – also moves off the caller thread. That only works because LogRecord is immutable and captures everything the formatter will need at creation time, including the caller’s thread name, which the writer thread has no way to recover later.

Then the queue fills, because eventually it does, and the framework has to choose:

Policy What the caller feels What you lose
Block log.debug parks until a slot frees, putting disk latency back into the request path – the exact thing the queue was for Nothing is lost, and that is the problem: a stalled disk now throttles checkout, so the logger can take down the service
Drop newest Nothing; the call returns immediately The records from the busiest moment, which is precisely the moment you will want to read
Drop oldest Nothing The start of the burst, including the first error that explains everything after it

The usual answer, and the one worth saying out loud: make the policy depend on the level. Block for ERROR, because a caller waiting two milliseconds is cheaper than not knowing why the service failed. Drop for DEBUG, because debug volume is exactly what saturates a queue and no single debug line is load-bearing. And count every drop in an AtomicLong that the service exports as a metric, so a gap in the log file is explainable rather than mysterious. Do not log the drop – writing “dropped 400 records” into a logger whose queue is full is a joke that writes itself. It belongs in observability plumbing, next to queue depth.

Shutdown is the other half of the same problem. A daemon writer thread lets the JVM exit with records still queued, so the last thing the process did before dying is the thing you cannot read. close() therefore puts a sentinel on the queue – ordered behind everything already waiting – joins the writer with a bounded timeout, and then closes the delegate so the file handle is flushed. The timeout is deliberate: shutdown that waits forever on a hung socket is its own incident. If the join times out, the remaining queue depth gets reported the same way drops do.

classDiagram
    class LogLevel {
        <<enumeration>>
        -int severity
        +isAtLeast(threshold) boolean
    }

    class LogRecord {
        -Instant timestamp
        -LogLevel level
        -String loggerName
        -String message
        -String threadName
        -Throwable throwable
    }

    class LogFormatter {
        <<interface>>
        +format(record) String
    }

    class PatternFormatter
    class JsonFormatter

    class Appender {
        <<interface>>
        +append(record)
        +getThreshold() LogLevel
        +close()
    }

    class ConsoleAppender {
        -LogFormatter formatter
        -LogLevel threshold
    }

    class FileAppender {
        -BufferedWriter writer
        -LogLevel threshold
    }

    class BufferedAppender {
        -Appender delegate
        -List~LogRecord~ buffer
    }

    class AsyncAppender {
        -Appender delegate
        -BlockingQueue~LogRecord~ queue
        -OverflowPolicy policy
        -AtomicLong dropped
        +getDroppedCount() long
    }

    class Logger {
        -String name
        -List~Appender~ appenders
        +isLoggable(level) boolean
        +debug(supplier)
        +info(message)
    }

    class LoggerRegistry {
        -Map~String LogLevel~ configuredLevels
        -Map~String CachedLevel~ cache
        +getLogger(name) Logger
        +setLevel(name level)
        +effectiveLevel(name) LogLevel
    }

    LogFormatter <|.. PatternFormatter
    LogFormatter <|.. JsonFormatter
    Appender <|.. ConsoleAppender
    Appender <|.. FileAppender
    Appender <|.. BufferedAppender
    Appender <|.. AsyncAppender
    AsyncAppender --> Appender : delegate
    BufferedAppender --> Appender : delegate
    ConsoleAppender --> LogFormatter
    FileAppender --> LogFormatter
    Logger --> LoggerRegistry : effective level
    Logger --> Appender : fan-out
    LoggerRegistry --> Logger : interns
    LogRecord --> LogLevel

💡 In a class diagram the dashed hollow arrow <|.. means “implements this interface” and the plain arrow --> means “holds a reference to”. AsyncAppender has both pointing at Appender, which is the shape of a decorator. Learn more →

Key classes:

  • LogLevel – an enum with an explicit int severity rather than relying on ordinal(). Severities are spaced by ten so a custom level can slot between two existing ones; ordinal() is positional and silently changes meaning the moment somebody reorders the enum.
  • LogRecord – the immutable unit that crosses the thread boundary. It takes its timestamp from an injected Clock and captures the caller’s thread name at construction, because by the time a formatter runs the calling thread may be serving a different request.
  • LogFormatter – the Strategy. It exists so that switching a file from a pattern line to JSON is a constructor argument, not a new appender class.
  • Appender – the destination interface, carrying its own threshold so the fan-out loop in Logger never has to know what any destination filters on. It extends AutoCloseable because a destination that buffers must be closeable.
  • BufferedAppender – the simple decorator: accumulate records, forward in batches, flush immediately on ERROR. It exists mainly to show that decorators stack, and that the stacking order is a real decision.
  • AsyncAppender – the interesting class. It owns the ArrayBlockingQueue, the writer thread, the overflow policy, the drop counter and a close() that actually drains. Everything hard about this problem lives here.
  • Logger – what callers hold. It owns the guard, the Supplier overload, and the fan-out loop that must not let one broken appender stop the others.
  • LoggerRegistry – interns one Logger per name, walks the name hierarchy to resolve effective levels, caches the result with a config version stamp, and owns the shared appender list.

Design Patterns

Pattern Where Why
Chain of Responsibility LoggerRegistry.resolve walking com.shop.orders up to the root First match wins, so one config entry governs an entire package subtree and the root terminates the walk
Decorator AsyncAppender and BufferedAppender wrapping any Appender Threading and batching are orthogonal to destination, so Async(Buffered(File)) composes without a AsyncBufferedFileAppender class
Strategy LogFormatter with PatternFormatter and JsonFormatter The same record renders differently per destination; a new wire format is a new class
Observer / fan-out Logger iterating its appender list One event, many independent subscribers, none of which can veto the others
Factory AppenderFactory.fromConfig building a stack from a config map Callers name a destination and a policy; wiring queue capacity, formatter and decorator order stays in one place
Singleton LoggerRegistry.global() A class acquires its logger in a static initialiser where nothing can be injected, so one well-known instance is the pragmatic answer – with costs, below

💡 Chain of Responsibility = pass a request along candidates until one takes it. Here the “request” is a question – what level applies to com.shop.orders? – and the links are ancestor names, so the first configured ancestor answers and the walk stops.

💡 Decorator = wrap an object in something implementing the same interface, adding behavior on the way through. AsyncAppender adds a thread, BufferedAppender adds batching, and because both are just Appender, the stack order is a configuration choice rather than a code change.

💡 Strategy = put interchangeable algorithms behind one interface so the holder can swap them. Every appender holds a LogFormatter and calls format(record), which is why the console can stay human-readable while the file emits JSON.

💡 Observer = one producer notifies many registered listeners. The appender list is the degenerate in-process form: no subscription protocol, just a list that Logger walks, and critically no listener can stop the notification reaching the next one.

💡 Factory = move construction into one place that knows how to assemble the parts. AppenderFactory is where “file, async, capacity 4096, drop DEBUG” becomes three nested objects, so no caller has to remember that buffering belongs inside the async wrapper.

💡 Singleton = exactly one instance, reachable globally. The registry is the one place in this design where it is defensible, and the price is real: a static registry is shared mutable state across tests, so setLevel in one test leaks into the next unless you reset it. Every class here takes its registry and its Clock as constructor arguments; global() is a convenience for production call sites, not the design. Prefer injection wherever you control construction.


Data Structures

Component Structure Why
Async handoff ArrayBlockingQueue<LogRecord> with fixed capacity Array-backed so enqueue is O(1) with no allocation per record; bounded so a stalled disk cannot grow the heap
Appender list CopyOnWriteArrayList<Appender> A fan-out in flight iterates a snapshot, so attaching an appender at runtime cannot throw ConcurrentModificationException mid-record
Effective-level cache ConcurrentHashMap<String, CachedLevel> keyed by logger name Turns an O(depth) string walk into one lookup; the entry carries a config version so a setLevel invalidates without a global clear()
Logger instances ConcurrentHashMap<String, Logger> plus computeIfAbsent One Logger per name, created once, so getLogger in a static field is cheap and identity is stable
Configured levels ConcurrentHashMap<String, LogLevel> holding only explicit entries The walk works precisely because absence is meaningful: no entry means “ask my parent”
Drop and depth counters AtomicLong Lock-free increment on the hot path; the numbers are metrics, not log lines

The consequential choice is the queue’s capacity, not its type. Unbounded is the tempting default and it is wrong: an unbounded queue converts a slow disk into an OutOfMemoryError, which takes the process down instead of taking the logs down. A fixed capacity turns the same failure into a decision you made on purpose – block, or drop and count. The number itself is a tradeoff between how long a burst you can absorb and how many records you are willing to lose on a hard kill, and the only way to pick it is to measure the burst you actually get.

💡 O(1) vs O(depth) = enqueueing a record costs the same whatever the queue holds, while resolving a.b.c.d.e without a cache touches one map entry per dotted segment. Caching is what keeps the hot path flat. Learn more →

💡 Copy-on-write = reads are free and never lock, while every write copies the whole array. Exactly right for an appender list, which is written once at startup and read on every log call, and exactly wrong for the record queue.


Complete Code

The Java tab is complete. The other three show what genuinely differs in that language – a frozen dataclass, a hand-rolled bounded queue, a single-threaded event loop – and name what they reuse from the Java tab instead of restating it.

LogLevel.java

An enum with an explicit numeric severity, so a threshold test is severity &gt;= threshold.severity. The numbers are spaced by ten on purpose: a FATAL or NOTICE level can be slotted in later without renumbering, which ordinal() could never survive.

package logging.core;

public enum LogLevel {
    TRACE(10), DEBUG(20), INFO(30), WARN(40), ERROR(50),
    /** Threshold-only value. No record is ever created at OFF. */
    OFF(Integer.MAX_VALUE);

    private final int severity;

    LogLevel(int severity) { this.severity = severity; }

    public int getSeverity() { return severity; }

    /** True when a record at this level clears the given threshold. */
    public boolean isAtLeast(LogLevel threshold) {
        return severity >= threshold.severity;
    }
}
from enum import Enum


class LogLevel(Enum):
    """Severity is explicit rather than positional, so a level can be inserted later."""

    TRACE, DEBUG, INFO, WARN, ERROR = 10, 20, 30, 40, 50
    OFF = 1 << 30                 # threshold-only

    def is_at_least(self, threshold: "LogLevel") -> bool:
        return self.value >= threshold.value
// A C++ enum class carries no behaviour, so the comparison is a free function.
enum class LogLevel : int {
    Trace = 10, Debug = 20, Info = 30, Warn = 40, Error = 50,
    Off = 1 << 30                 // threshold-only
};

inline bool isAtLeast(LogLevel level, LogLevel threshold) {
    return static_cast<int>(level) >= static_cast<int>(threshold);
}

const char* levelName(LogLevel level);      // TRACE, DEBUG, INFO, WARN, ERROR, OFF
// A frozen lookup rather than a bare string, because the severity is the point.
const LogLevel = Object.freeze({
    TRACE: Object.freeze({ name: "TRACE", severity: 10 }),
    DEBUG: Object.freeze({ name: "DEBUG", severity: 20 }),
    INFO:  Object.freeze({ name: "INFO",  severity: 30 }),
    WARN:  Object.freeze({ name: "WARN",  severity: 40 }),
    ERROR: Object.freeze({ name: "ERROR", severity: 50 }),
    OFF:   Object.freeze({ name: "OFF",   severity: Number.MAX_SAFE_INTEGER })
});

const isAtLeast = (level, threshold) => level.severity >= threshold.severity;

LogRecord.java

The immutable unit that crosses the thread boundary. Two details earn their keep: the timestamp comes from an injected Clock so tests are deterministic, and the caller’s thread name is captured here rather than read later – by the time the writer thread formats this record, the calling thread is serving a different request.

package logging.core;

import java.time.Instant;
import java.util.Objects;

/** Immutable snapshot of one event. Safe to hand across a queue with no lock. */
public final class LogRecord {
    private final Instant timestamp;
    private final LogLevel level;
    private final String loggerName;
    private final String message;
    private final String threadName;
    private final Throwable throwable;   // nullable

    public LogRecord(Instant timestamp, LogLevel level, String loggerName,
                     String message, String threadName, Throwable throwable) {
        this.timestamp = Objects.requireNonNull(timestamp, "timestamp");
        this.level = Objects.requireNonNull(level, "level");
        this.loggerName = Objects.requireNonNull(loggerName, "loggerName");
        this.message = Objects.requireNonNull(message, "message");
        this.threadName = Objects.requireNonNull(threadName, "threadName");
        this.throwable = throwable;
    }

    public Instant getTimestamp() { return timestamp; }
    public LogLevel getLevel() { return level; }
    public String getLoggerName() { return loggerName; }
    public String getMessage() { return message; }
    public String getThreadName() { return threadName; }
    public Throwable getThrowable() { return throwable; }
    public boolean hasThrowable() { return throwable != null; }

    // Value equality over the scalar fields. The throwable is deliberately left out:
    // Throwable compares by identity, so including it would make a record unequal to
    // a faithful copy of itself.
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof LogRecord)) return false;
        LogRecord other = (LogRecord) o;
        return level == other.level
                && timestamp.equals(other.timestamp)
                && loggerName.equals(other.loggerName)
                && message.equals(other.message)
                && threadName.equals(other.threadName);
    }

    @Override
    public int hashCode() {
        return Objects.hash(timestamp, level, loggerName, message, threadName);
    }

    @Override
    public String toString() { return level + " " + loggerName + " - " + message; }
}
from dataclasses import dataclass, field
from datetime import datetime
from typing import Optional


@dataclass(frozen=True)
class LogRecord:
    """frozen=True buys immutability, value equality and a hash in one line."""

    timestamp: datetime
    level: LogLevel
    logger_name: str
    message: str
    thread_name: str
    # Excluded from equality: exceptions compare by identity.
    throwable: Optional[BaseException] = field(default=None, compare=False)

    def has_throwable(self) -> bool:
        return self.throwable is not None
// Every member is const, which is how C++ says "immutable": assignment stops
// compiling, while the move-construct the queue needs still works. The accessors
// are the obvious const getters, one per field, plus hasThrowable().
class LogRecord {
public:
    LogRecord(std::chrono::system_clock::time_point ts, LogLevel level,
              std::string loggerName, std::string message, std::string threadName,
              std::exception_ptr throwable = nullptr)
        : timestamp_(ts), level_(level), loggerName_(std::move(loggerName)),
          message_(std::move(message)), threadName_(std::move(threadName)),
          throwable_(std::move(throwable)) {
    }

    LogLevel level() const { return level_; }
    const std::string& message() const { return message_; }

private:
    const std::chrono::system_clock::time_point timestamp_;
    const LogLevel level_;
    const std::string loggerName_;
    const std::string message_;
    const std::string threadName_;
    const std::exception_ptr throwable_;
};
// Object.freeze is the closest thing to immutability without a build step.
class LogRecord {
    constructor(timestamp, level, loggerName, message, threadName, error = null) {
        this.timestamp = timestamp;
        this.level = level;
        this.loggerName = loggerName;
        this.message = message;
        // "main" in a plain Node process, a worker id once worker_threads is in play.
        this.threadName = threadName;
        this.error = error;
        Object.freeze(this);
    }

    hasError() { return this.error !== null; }
}

LogFormatter.java

The Strategy interface plus its two implementations, shown together. Formatting is pure CPU work over a record, which is why it sits behind an interface and why AsyncAppender can push it onto the writer thread.

package logging.format;

import logging.core.LogRecord;

public interface LogFormatter {
    /** Runs on whichever thread the appender is on -- the writer thread when async. */
    String format(LogRecord record);
}

// --- PatternFormatter.java -------------------------------------------------
package logging.format;

import logging.core.LogRecord;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.time.format.DateTimeFormatter;

/** 2026-11-12T09:15:00Z [http-7] INFO  com.shop.orders - order OD-1001 placed */
public class PatternFormatter implements LogFormatter {

    @Override
    public String format(LogRecord record) {
        StringBuilder sb = new StringBuilder(160);
        sb.append(DateTimeFormatter.ISO_INSTANT.format(record.getTimestamp()))
          .append(" [").append(record.getThreadName()).append("] ")
          .append(String.format("%-5s", record.getLevel()))
          .append(' ').append(record.getLoggerName())
          .append(" - ").append(record.getMessage());
        if (record.hasThrowable()) {
            sb.append(System.lineSeparator()).append(stackTraceOf(record.getThrowable()));
        }
        return sb.toString();
    }

    private static String stackTraceOf(Throwable t) {
        StringWriter buffer = new StringWriter();
        t.printStackTrace(new PrintWriter(buffer));
        return buffer.toString();
    }
}

// --- JsonFormatter.java ---------------------------------------------------
package logging.format;

import logging.core.LogRecord;

/** One JSON object per line, which is what a log shipper wants to ingest. */
public class JsonFormatter implements LogFormatter {

    @Override
    public String format(LogRecord record) {
        StringBuilder sb = new StringBuilder(200).append('{');
        field(sb, "ts", record.getTimestamp().toString()).append(',');
        field(sb, "level", record.getLevel().name()).append(',');
        field(sb, "logger", record.getLoggerName()).append(',');
        field(sb, "thread", record.getThreadName()).append(',');
        field(sb, "msg", record.getMessage());
        if (record.hasThrowable()) {
            sb.append(',');
            field(sb, "error", record.getThrowable().toString());
        }
        return sb.append('}').toString();
    }

    private static StringBuilder field(StringBuilder sb, String key, String value) {
        return sb.append('"').append(key).append("\":\"").append(escape(value)).append('"');
    }

    /** Enough escaping to stay valid JSON; production delegates to a JSON library. */
    private static String escape(String value) {
        return value.replace("\\", "\\\\")
                    .replace("\"", "\\\"")
                    .replace("\n", "\\n")
                    .replace("\r", "\\r")
                    .replace("\t", "\\t");
    }
}
import json
import traceback
from abc import ABC, abstractmethod


class LogFormatter(ABC):
    @abstractmethod
    def format(self, record: LogRecord) -> str:
        ...


class PatternFormatter(LogFormatter):
    def format(self, record: LogRecord) -> str:
        head = (f"{record.timestamp.isoformat()} [{record.thread_name}] "
                f"{record.level.name:<5} {record.logger_name} - {record.message}")
        if record.throwable is None:
            return head
        return head + "\n" + "".join(traceback.format_exception(record.throwable))


class JsonFormatter(LogFormatter):
    def format(self, record: LogRecord) -> str:
        payload = dict(ts=record.timestamp.isoformat(), level=record.level.name,
                       logger=record.logger_name, thread=record.thread_name,
                       msg=record.message)
        if record.throwable is not None:
            payload["error"] = repr(record.throwable)
        return json.dumps(payload, separators=(",", ":"))   # escaping comes free
class LogFormatter {
public:
    virtual ~LogFormatter() = default;
    virtual std::string format(const LogRecord& record) const = 0;
};

class PatternFormatter : public LogFormatter {
public:
    std::string format(const LogRecord& record) const override {
        const auto seconds = std::chrono::system_clock::to_time_t(record.timestamp());
        std::tm utc;
        gmtime_r(&seconds, &utc);
        std::ostringstream out;
        out << std::put_time(&utc, "%FT%TZ") << " [" << record.threadName() << "] "
            << std::left << std::setw(5) << levelName(record.level()) << " "
            << record.loggerName() << " - " << record.message();
        return out.str();
    }
};

// JsonFormatter mirrors the Java tab: the same fields, one object per line, with
// quote and backslash escaping done by hand or by a JSON library.
class PatternFormatter {
    format(record) {
        const head = `${record.timestamp.toISOString()} [${record.threadName}] `
            + `${record.level.name.padEnd(5)} ${record.loggerName} - ${record.message}`;
        return record.hasError() ? `${head}\n${record.error.stack}` : head;
    }
}

class JsonFormatter {
    format(record) {
        const payload = {
            ts: record.timestamp.toISOString(), level: record.level.name,
            logger: record.loggerName, thread: record.threadName, msg: record.message
        };
        if (record.hasError()) payload.error = String(record.error);
        return JSON.stringify(payload);
    }
}

Appender.java

The destination interface, its two concrete implementations, and the factory that assembles a stack from config. Note where the threshold check lives: each appender gates itself, so the fan-out loop in Logger never learns what any destination filters on, and a destination can be attached at runtime carrying its own floor.

package logging.appender;

import logging.core.LogLevel;
import logging.core.LogRecord;

public interface Appender extends AutoCloseable {

    /** Called for every record that passed the logger's guard. Must never throw. */
    void append(LogRecord record);

    /** This destination's own floor. The append call is what enforces it. */
    LogLevel getThreshold();

    /** Flush and release. Must be idempotent -- shutdown paths call it twice. */
    @Override
    void close();
}

// --- ConsoleAppender.java -------------------------------------------------
package logging.appender;

import logging.core.LogLevel;
import logging.core.LogRecord;
import logging.format.LogFormatter;

import java.io.PrintStream;

public class ConsoleAppender implements Appender {
    private final LogFormatter formatter;
    private final LogLevel threshold;
    private final PrintStream out;
    private final PrintStream err;

    public ConsoleAppender(LogFormatter formatter, LogLevel threshold) {
        this(formatter, threshold, System.out, System.err);
    }

    // The streams are parameters so a test can pass a ByteArrayOutputStream.
    public ConsoleAppender(LogFormatter formatter, LogLevel threshold,
                           PrintStream out, PrintStream err) {
        this.formatter = formatter;
        this.threshold = threshold;
        this.out = out;
        this.err = err;
    }

    @Override
    public void append(LogRecord record) {
        if (!record.getLevel().isAtLeast(threshold)) return;
        String line = formatter.format(record);
        PrintStream sink = record.getLevel().isAtLeast(LogLevel.WARN) ? err : out;
        // One record, one write. Without the lock two threads interleave halves of
        // a line and the output stops being parseable.
        synchronized (this) {
            sink.println(line);
        }
    }

    @Override public LogLevel getThreshold() { return threshold; }

    @Override
    public synchronized void close() {
        out.flush();
        err.flush();
    }
}

// --- FileAppender.java ----------------------------------------------------
package logging.appender;

import logging.core.LogLevel;
import logging.core.LogRecord;
import logging.format.LogFormatter;

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class FileAppender implements Appender {
    private final LogFormatter formatter;
    private final LogLevel threshold;
    private final Path path;
    private final BufferedWriter writer;
    private boolean closed = false;

    public FileAppender(Path path, LogFormatter formatter, LogLevel threshold)
            throws IOException {
        this.path = path;
        this.formatter = formatter;
        this.threshold = threshold;
        this.writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8,
                StandardOpenOption.CREATE, StandardOpenOption.APPEND);
    }

    @Override
    public synchronized void append(LogRecord record) {
        if (closed || !record.getLevel().isAtLeast(threshold)) return;
        try {
            writer.write(formatter.format(record));
            writer.newLine();
            // Buffered for throughput, flushed for anything we cannot afford to lose.
            if (record.getLevel().isAtLeast(LogLevel.ERROR)) writer.flush();
        } catch (IOException e) {
            // A logger must not throw into business code: the caller can do nothing
            // useful with this. Report on a side channel and keep going.
            System.err.println("FileAppender " + path + " failed: " + e.getMessage());
        }
    }

    @Override public LogLevel getThreshold() { return threshold; }

    @Override
    public synchronized void close() {
        if (closed) return;
        closed = true;
        try {
            writer.flush();
            writer.close();
        } catch (IOException e) {
            System.err.println("FileAppender " + path + " close failed: " + e.getMessage());
        }
    }
}

// --- AppenderFactory.java -------------------------------------------------
package logging.appender;

import logging.core.LogLevel;
import logging.format.JsonFormatter;
import logging.format.LogFormatter;
import logging.format.PatternFormatter;

import java.io.IOException;
import java.nio.file.Path;
import java.util.Map;

/** Turns a flat config map into a decorator stack so callers never nest by hand. */
public final class AppenderFactory {

    private AppenderFactory() { }

    public static Appender fromConfig(Map<String, String> config) throws IOException {
        LogLevel threshold = LogLevel.valueOf(config.getOrDefault("level", "INFO"));
        LogFormatter formatter = "json".equals(config.get("format"))
                ? new JsonFormatter() : new PatternFormatter();

        Appender destination = "file".equals(config.get("type"))
                ? new FileAppender(Path.of(config.get("path")), formatter, threshold)
                : new ConsoleAppender(formatter, threshold);

        int batchSize = Integer.parseInt(config.getOrDefault("batchSize", "0"));
        if (batchSize > 1) destination = new BufferedAppender(destination, batchSize);

        int capacity = Integer.parseInt(config.getOrDefault("queueCapacity", "0"));
        if (capacity > 0) {
            destination = new AsyncAppender(destination, capacity,
                    AsyncAppender.OverflowPolicy.valueOf(
                            config.getOrDefault("overflow", "DROP_NEWEST")),
                    LogLevel.valueOf(config.getOrDefault("blockAbove", "ERROR")));
        }

        // Async outermost, buffering inside it, so the batching happens on the writer
        // thread. Swap the order and you batch on the caller's thread, which is the
        // latency you were trying to get rid of.
        return destination;
    }
}
import sys
import threading
from abc import ABC, abstractmethod


class Appender(ABC):
    """One destination, gating itself on its own threshold."""

    def __init__(self, threshold: LogLevel) -> None:
        self._threshold = threshold

    @property
    def threshold(self) -> LogLevel:
        return self._threshold

    @abstractmethod
    def append(self, record: LogRecord) -> None:
        ...

    def close(self) -> None:
        """Idempotent by contract."""


class ConsoleAppender(Appender):
    def __init__(self, formatter: LogFormatter, threshold: LogLevel) -> None:
        super().__init__(threshold)
        self._formatter = formatter
        self._lock = threading.Lock()

    def append(self, record: LogRecord) -> None:
        if not record.level.is_at_least(self._threshold):
            return
        sink = sys.stderr if record.level.is_at_least(LogLevel.WARN) else sys.stdout
        with self._lock:                   # one record, one undivided write
            print(self._formatter.format(record), file=sink)


# FileAppender and appender_from_config mirror the Java tab: a handle opened in
# append mode, a lock per write, flush on ERROR, an OSError reported to stderr
# instead of raised, and a factory that nests BufferedAppender inside AsyncAppender.
class Appender {
public:
    virtual ~Appender() = default;
    virtual void append(const LogRecord& record) = 0;
    virtual LogLevel threshold() const = 0;
    virtual void close() = 0;              // must be idempotent
};

class ConsoleAppender : public Appender {
public:
    ConsoleAppender(std::shared_ptr<LogFormatter> formatter, LogLevel threshold)
        : formatter_(std::move(formatter)), threshold_(threshold) {
    }

    void append(const LogRecord& record) override {
        if (!isAtLeast(record.level(), threshold_)) return;
        const std::string line = formatter_->format(record);
        std::lock_guard<std::mutex> guard(mutex_);      // one record, one write
        if (isAtLeast(record.level(), LogLevel::Warn)) std::cerr << line << "\n";
        else std::cout << line << "\n";
    }

    LogLevel threshold() const override { return threshold_; }

    void close() override {
        std::cout.flush();
        std::cerr.flush();
    }

private:
    std::shared_ptr<LogFormatter> formatter_;
    LogLevel threshold_;
    mutable std::mutex mutex_;
};

// FileAppender mirrors the Java tab over an std::ofstream opened in append mode.
// Every appender is held by shared_ptr, because a decorator outlives the scope
// that built it.
const fs = require("node:fs");

class ConsoleAppender {
    #formatter;
    #threshold;

    constructor(formatter, threshold) {
        this.#formatter = formatter;
        this.#threshold = threshold;
    }

    append(record) {
        if (!isAtLeast(record.level, this.#threshold)) return;
        const line = this.#formatter.format(record);
        // One write syscall per call, so lines cannot interleave and no lock is needed.
        if (isAtLeast(record.level, LogLevel.WARN)) console.error(line);
        else console.log(line);
    }

    get threshold() { return this.#threshold; }

    close() { /* the runtime flushes stdout on exit */ }
}

class FileAppender {
    #formatter;
    #threshold;
    #stream;

    constructor(path, formatter, threshold) {
        this.#formatter = formatter;
        this.#threshold = threshold;
        this.#stream = fs.createWriteStream(path, { flags: "a" });
        // An error event rather than a throw: the logger never breaks its caller.
        this.#stream.on("error", (err) =>
            process.stderr.write(`FileAppender failed: ${err}\n`));
    }

    append(record) {
        if (!isAtLeast(record.level, this.#threshold)) return;
        this.#stream.write(this.#formatter.format(record) + "\n");
    }

    get threshold() { return this.#threshold; }

    close() { this.#stream.end(); }
}

BufferedAppender.java

The simple decorator, here mainly to prove that decorators stack and that the stacking order is a real decision. One thing it deliberately lacks: a time-based flush. A batch that never fills never writes, so a production version also flushes on a timer, which is a second thread and a second shutdown path.

package logging.appender;

import logging.core.LogLevel;
import logging.core.LogRecord;

import java.util.ArrayList;
import java.util.List;

/** Decorator: hold records back and forward them to the delegate in batches. */
public class BufferedAppender implements Appender {
    private final Appender delegate;
    private final int batchSize;
    private final List<LogRecord> buffer;

    public BufferedAppender(Appender delegate, int batchSize) {
        if (batchSize < 1) throw new IllegalArgumentException("batchSize must be 1 or more");
        this.delegate = delegate;
        this.batchSize = batchSize;
        this.buffer = new ArrayList<>(batchSize);
    }

    @Override
    public synchronized void append(LogRecord record) {
        buffer.add(record);
        // An ERROR never waits for a batch to fill. If the process dies in the next
        // millisecond, that is exactly the record you needed on disk.
        if (buffer.size() >= batchSize || record.getLevel().isAtLeast(LogLevel.ERROR)) {
            flushLocked();
        }
    }

    /** Caller holds the monitor. */
    private void flushLocked() {
        for (LogRecord buffered : buffer) delegate.append(buffered);
        buffer.clear();
    }

    @Override public LogLevel getThreshold() { return delegate.getThreshold(); }

    @Override
    public synchronized void close() {
        flushLocked();        // a half-full batch is still records
        delegate.close();     // decorators close downward, exactly once
    }
}
import threading
class BufferedAppender(Appender):
    """Decorator: forward records to the delegate in batches."""

    def __init__(self, delegate: Appender, batch_size: int) -> None:
        super().__init__(delegate.threshold)
        self._delegate, self._batch_size = delegate, batch_size
        self._buffer: list[LogRecord] = []
        self._lock = threading.Lock()

    def append(self, record: LogRecord) -> None:
        with self._lock:
            self._buffer.append(record)
            full = len(self._buffer) >= self._batch_size
            if full or record.level.is_at_least(LogLevel.ERROR):
                self._flush_locked()       # an ERROR never waits for a batch

    def _flush_locked(self) -> None:
        for buffered in self._buffer:
            self._delegate.append(buffered)
        self._buffer.clear()

    def close(self) -> None:
        with self._lock:
            self._flush_locked()           # a half-full batch is still records
        self._delegate.close()
class BufferedAppender : public Appender {
public:
    BufferedAppender(std::shared_ptr<Appender> delegate, std::size_t batchSize)
        : delegate_(std::move(delegate)), batchSize_(batchSize) {
        buffer_.reserve(batchSize);
    }

    void append(const LogRecord& record) override {
        std::lock_guard<std::mutex> guard(mutex_);
        buffer_.push_back(record);
        const bool urgent = isAtLeast(record.level(), LogLevel::Error);
        if (buffer_.size() >= batchSize_ || urgent) flushLocked();
    }

    LogLevel threshold() const override { return delegate_->threshold(); }

    void close() override {
        std::lock_guard<std::mutex> guard(mutex_);
        flushLocked();
        delegate_->close();
    }

private:
    void flushLocked() {
        for (const auto& buffered : buffer_) delegate_->append(buffered);
        buffer_.clear();
    }

    std::shared_ptr<Appender> delegate_;
    std::size_t batchSize_;
    std::vector<LogRecord> buffer_;
    std::mutex mutex_;
};
class BufferedAppender {
    #delegate;
    #batchSize;
    #buffer = [];

    constructor(delegate, batchSize) {
        this.#delegate = delegate;
        this.#batchSize = batchSize;
    }

    append(record) {
        this.#buffer.push(record);
        const urgent = isAtLeast(record.level, LogLevel.ERROR);
        if (this.#buffer.length >= this.#batchSize || urgent) this.#flush();
    }

    #flush() {
        const batch = this.#buffer.splice(0, this.#buffer.length);
        for (const buffered of batch) this.#delegate.append(buffered);
    }

    get threshold() { return this.#delegate.threshold; }

    close() {
        this.#flush();
        this.#delegate.close();
    }
}

AsyncAppender.java

The class the whole problem is really about. It owns a bounded queue, one writer thread, the overflow policy, the drop counter and a close() that drains. Read it for four things: the fast path is a single non-blocking offer, the full path branches on level before it branches on policy, the drain loop survives a bad record, and the shutdown sentinel enters the queue behind the backlog so closing writes everything already waiting.

package logging.appender;

import logging.core.LogLevel;
import logging.core.LogRecord;

import java.time.Instant;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Decorator that moves formatting and I/O off the caller's thread.
 *
 * The caller does one bounded offer and returns; a single writer thread drains into
 * the delegate. The only genuinely hard decision is what happens when the queue is
 * full, which is why the policy is a constructor argument rather than a default
 * buried in the class.
 */
public class AsyncAppender implements Appender {

    public enum OverflowPolicy { BLOCK, DROP_NEWEST, DROP_OLDEST }

    /**
     * Shutdown sentinel, compared by identity. It is enqueued like any other record,
     * so it sits behind everything already waiting -- which is what makes close() a
     * drain rather than a discard.
     */
    private static final LogRecord SHUTDOWN = new LogRecord(
            Instant.EPOCH, LogLevel.OFF, "$shutdown", "", "$shutdown", null);

    private static final long DRAIN_TIMEOUT_MILLIS = 5_000L;

    private final Appender delegate;
    private final BlockingQueue<LogRecord> queue;
    private final OverflowPolicy policy;
    private final LogLevel blockAbove;
    private final Thread writer;

    private final AtomicLong dropped = new AtomicLong();
    private final AtomicLong written = new AtomicLong();
    private volatile boolean running = true;

    public AsyncAppender(Appender delegate, int capacity,
                         OverflowPolicy policy, LogLevel blockAbove) {
        if (capacity < 1) throw new IllegalArgumentException("capacity must be 1 or more");
        this.delegate = delegate;
        this.queue = new ArrayBlockingQueue<>(capacity);   // bounded on purpose
        this.policy = policy;
        this.blockAbove = blockAbove;
        this.writer = new Thread(this::drainLoop, "log-writer");
        // Daemon so a forgotten close() cannot keep the JVM alive. The cost is that
        // the JVM can exit with records queued, which the hook below prevents.
        this.writer.setDaemon(true);
        this.writer.start();
    }

    /**
     * Opt-in rather than automatic. Registering a hook inside the constructor
     * publishes `this` to another thread before construction has finished, and a
     * shutdown hook can never be removed, so one per instance leaks. Call this once,
     * from whatever owns the appender's lifecycle.
     */
    public void registerShutdownHook() {
        Runtime.getRuntime().addShutdownHook(new Thread(this::close, "log-writer-hook"));
    }

    @Override
    public void append(LogRecord record) {
        if (!running) {                    // already closing: do not refill the queue
            dropped.incrementAndGet();
            return;
        }
        if (queue.offer(record)) return;   // the fast path: O(1), never blocks
        handleFull(record);
    }

    /** Everything interesting about this class is in these ten lines. */
    private void handleFull(LogRecord record) {
        // Level first, policy second. An ERROR is worth making the caller wait for;
        // the thousandth DEBUG of a burst is not.
        if (record.getLevel().isAtLeast(blockAbove) || policy == OverflowPolicy.BLOCK) {
            putBlocking(record);
            return;
        }
        if (policy == OverflowPolicy.DROP_OLDEST) {
            if (queue.poll() != null) dropped.incrementAndGet();   // the stalest goes
            if (queue.offer(record)) return;
        }
        // DROP_NEWEST, or a DROP_OLDEST that lost the race for the slot it just freed.
        dropped.incrementAndGet();
    }

    private void putBlocking(LogRecord record) {
        try {
            queue.put(record);             // the caller parks until a slot frees
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();   // never swallow an interrupt
            dropped.incrementAndGet();
        }
    }

    private void drainLoop() {
        while (true) {
            LogRecord record;
            try {
                record = queue.take();     // parks when idle, so the thread never spins
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return;
            }
            if (record == SHUTDOWN) return;        // identity, not equals
            try {
                delegate.append(record);           // format plus I/O, off the caller
                written.incrementAndGet();
            } catch (RuntimeException e) {
                // One poisonous record must not kill the writer thread. If it did,
                // logging would stop for the rest of the process and nothing would
                // say so -- the worst failure mode this class has.
                System.err.println("log writer error: " + e);
            }
        }
    }

    @Override
    public synchronized void close() {
        if (!running) return;              // idempotent: owner and hook both call it
        running = false;
        try {
            queue.put(SHUTDOWN);           // behind the backlog, not ahead of it
            writer.join(DRAIN_TIMEOUT_MILLIS);   // bounded: a hung socket must not
                                                 // wedge shutdown forever
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        // A caller already past the running check can land a record behind the
        // sentinel. Reporting the depth makes that visible instead of silent.
        if (writer.isAlive() || !queue.isEmpty()) {
            System.err.println("log writer finished with " + queue.size()
                    + " records unwritten");
        }
        delegate.close();                  // this is where the file is actually flushed
        long lost = dropped.get();
        if (lost > 0) System.err.println("AsyncAppender dropped " + lost + " records");
    }

    @Override public LogLevel getThreshold() { return delegate.getThreshold(); }

    // Metrics, not log lines. Logging a drop into a saturated logger goes nowhere.
    public long getDroppedCount() { return dropped.get(); }
    public long getWrittenCount() { return written.get(); }
    public int getQueueDepth() { return queue.size(); }
}
import queue
import sys
import threading

# Threads are the right tool here even with the GIL: the writer spends its life
# blocked in a write syscall, which releases the GIL for everyone else.

_SHUTDOWN = object()        # sentinel, compared with `is`


class AsyncAppender(Appender):
    """Decorator: hand the record to a writer thread and return."""

    def __init__(self, delegate: Appender, capacity: int,
                 policy: str = "drop_newest",
                 block_above: LogLevel = LogLevel.ERROR) -> None:
        super().__init__(delegate.threshold)
        self._delegate, self._policy, self._block_above = delegate, policy, block_above
        self._queue: queue.Queue = queue.Queue(maxsize=capacity)    # bounded
        self._dropped = 0
        self._counter_lock = threading.Lock()
        self._running = True
        self._writer = threading.Thread(
            target=self._drain_loop, name="log-writer", daemon=True)
        self._writer.start()

    def append(self, record: LogRecord) -> None:
        if not self._running:
            self._count_drop()
            return
        try:
            self._queue.put_nowait(record)      # fast path
            return
        except queue.Full:
            pass
        # Level first, policy second.
        if record.level.is_at_least(self._block_above) or self._policy == "block":
            self._queue.put(record)             # the caller waits
            return
        if self._policy == "drop_oldest":
            try:
                self._queue.get_nowait()
                self._count_drop()
                self._queue.put_nowait(record)
                return
            except (queue.Empty, queue.Full):
                pass
        self._count_drop()

    def _count_drop(self) -> None:
        with self._counter_lock:
            self._dropped += 1

    def _drain_loop(self) -> None:
        while True:
            record = self._queue.get()
            if record is _SHUTDOWN:
                return
            try:
                self._delegate.append(record)
            except Exception as exc:            # one bad record must not kill the writer
                print(f"log writer error: {exc}", file=sys.stderr)

    def close(self) -> None:
        if not self._running:
            return
        self._running = False
        self._queue.put(_SHUTDOWN)              # behind the backlog
        self._writer.join(timeout=5.0)
        self._delegate.close()
        if self._dropped:
            print(f"AsyncAppender dropped {self._dropped} records", file=sys.stderr)

    @property
    def dropped_count(self) -> int:
        return self._dropped

    @property
    def queue_depth(self) -> int:
        return self._queue.qsize()
#pragma once
#include <condition_variable>
#include <deque>
#include <iostream>
#include <mutex>
#include <thread>
#include "Appender.h"

// There is no ArrayBlockingQueue in the standard library, so the bound is enforced
// by hand: a deque, a mutex and two condition variables -- one for "not full", one
// for "not empty". That is what ArrayBlockingQueue is underneath anyway.
class AsyncAppender : public Appender {
public:
    enum class OverflowPolicy { Block, DropNewest, DropOldest };

    AsyncAppender(std::shared_ptr<Appender> delegate, std::size_t capacity,
                  OverflowPolicy policy, LogLevel blockAbove)
        : delegate_(std::move(delegate)), capacity_(capacity),
          policy_(policy), blockAbove_(blockAbove) {
        writer_ = std::thread([this] { drainLoop(); });
    }

    ~AsyncAppender() override { close(); }     // RAII: the destructor drains

    void append(const LogRecord& record) override {
        std::unique_lock<std::mutex> lock(mutex_);
        if (closing_) return;
        if (buffer_.size() < capacity_) {                  // fast path
            push(std::move(lock), record);
            return;
        }
        const bool mustKeep = isAtLeast(record.level(), blockAbove_)
                           || policy_ == OverflowPolicy::Block;
        if (mustKeep) {
            notFull_.wait(lock, [this] { return buffer_.size() < capacity_; });
            push(std::move(lock), record);
            return;
        }
        if (policy_ == OverflowPolicy::DropOldest) {
            buffer_.pop_front();
            ++dropped_;
            push(std::move(lock), record);
            return;
        }
        ++dropped_;                                        // DropNewest
    }

    LogLevel threshold() const override { return delegate_->threshold(); }

    void close() override {
        std::unique_lock<std::mutex> lock(mutex_);
        if (closing_) return;
        closing_ = true;
        lock.unlock();
        notEmpty_.notify_all();
        if (writer_.joinable()) writer_.join();            // drains first
        delegate_->close();
        if (dropped_ > 0) {
            std::cerr << "AsyncAppender dropped " << dropped_ << " records\n";
        }
    }

    std::size_t droppedCount() const { return dropped_; }

private:
    void push(std::unique_lock<std::mutex> lock, const LogRecord& record) {
        buffer_.push_back(record);
        lock.unlock();
        notEmpty_.notify_one();
    }

    void drainLoop() {
        while (true) {
            std::unique_lock<std::mutex> lock(mutex_);
            notEmpty_.wait(lock, [this] { return !buffer_.empty() || closing_; });
            if (buffer_.empty()) return;                   // empty and closing
            LogRecord record = buffer_.front();
            buffer_.pop_front();
            lock.unlock();
            notFull_.notify_one();
            try {
                delegate_->append(record);
            } catch (const std::exception& e) {
                std::cerr << "log writer error: " << e.what() << "\n";
            }
        }
    }

    std::shared_ptr<Appender> delegate_;
    std::size_t capacity_;
    OverflowPolicy policy_;
    LogLevel blockAbove_;
    std::deque<LogRecord> buffer_;
    mutable std::mutex mutex_;
    std::condition_variable notEmpty_;
    std::condition_variable notFull_;
    std::thread writer_;
    std::size_t dropped_ = 0;
    bool closing_ = false;
};
// Node runs one JavaScript thread, so "async" here means "off the current tick":
// the caller pushes and returns, and a scheduled drain does the writing. Note what
// that removes from the menu -- there is no way to block a single-threaded runtime,
// so BLOCK is not an option, which makes the drop policy unavoidable rather than
// merely advisable. For real parallelism the writer moves into a worker_threads
// Worker and the queue becomes a MessagePort.
class AsyncAppender {
    #delegate;
    #capacity;
    #policy;
    #blockAbove;
    #buffer = [];
    #dropped = 0;
    #scheduled = false;
    #closed = false;

    constructor(delegate, capacity, policy, blockAbove) {
        this.#delegate = delegate;
        this.#capacity = capacity;
        this.#policy = policy;              // "drop_newest" or "drop_oldest"
        this.#blockAbove = blockAbove;
    }

    append(record) {
        if (this.#closed) {
            this.#dropped++;
            return;
        }
        if (this.#buffer.length >= this.#capacity) {
            // Anything at or above blockAbove is written inline instead of dropped:
            // the caller eats the latency, which beats losing the error.
            if (isAtLeast(record.level, this.#blockAbove)) {
                this.#delegate.append(record);
                return;
            }
            if (this.#policy !== "drop_oldest") {
                this.#dropped++;
                return;
            }
            this.#buffer.shift();
            this.#dropped++;
        }
        this.#buffer.push(record);
        this.#scheduleDrain();
    }

    #scheduleDrain() {
        if (this.#scheduled) return;
        this.#scheduled = true;
        setImmediate(() => this.#drain());
    }

    #drain() {
        this.#scheduled = false;
        const batch = this.#buffer.splice(0, this.#buffer.length);
        for (const record of batch) {
            try {
                this.#delegate.append(record);
            } catch (err) {
                process.stderr.write(`log writer error: ${err}\n`);
            }
        }
        if (this.#buffer.length > 0) this.#scheduleDrain();
    }

    get threshold() { return this.#delegate.threshold; }

    close() {
        if (this.#closed) return;
        this.#closed = true;
        this.#drain();                      // synchronous final drain
        this.#delegate.close();
        if (this.#dropped > 0) {
            process.stderr.write(`AsyncAppender dropped ${this.#dropped} records\n`);
        }
    }

    get droppedCount() { return this.#dropped; }
    get queueDepth() { return this.#buffer.length; }
}

Logger.java

What callers hold. Three things are load-bearing: the guard runs before any record exists, the Supplier overload lets the caller skip string building without writing an if, and the fan-out loop swallows a failing appender so a broken console cannot cost you the file.

package logging.core;

import logging.appender.Appender;

import java.time.Clock;
import java.util.List;
import java.util.function.Supplier;

public class Logger {
    private final String name;
    private final LoggerRegistry registry;
    private final List<Appender> appenders;    // the registry's CopyOnWriteArrayList
    private final Clock clock;

    // Package-private: loggers are interned by the registry, never built by callers.
    Logger(String name, LoggerRegistry registry, List<Appender> appenders, Clock clock) {
        this.name = name;
        this.registry = registry;
        this.appenders = appenders;
        this.clock = clock;
    }

    public String getName() { return name; }

    /**
     * The guard. Public because the cheapest way to avoid building a message is for
     * the call site to ask first:
     *   if (log.isLoggable(LogLevel.DEBUG)) log.debug("cart=" + cart);
     */
    public boolean isLoggable(LogLevel level) {
        return level.isAtLeast(registry.effectiveLevel(name));
    }

    public void trace(String message) { log(LogLevel.TRACE, message, null); }
    public void debug(String message) { log(LogLevel.DEBUG, message, null); }
    public void info(String message)  { log(LogLevel.INFO, message, null); }
    public void warn(String message)  { log(LogLevel.WARN, message, null); }
    public void error(String message) { log(LogLevel.ERROR, message, null); }
    public void error(String message, Throwable t) { log(LogLevel.ERROR, message, t); }

    // Supplier overloads. log.debug(() -> "cart=" + cart) costs one lambda when
    // debug is off, instead of a concatenation, a cart walk and a discarded string.
    public void trace(Supplier<String> message) { log(LogLevel.TRACE, message, null); }
    public void debug(Supplier<String> message) { log(LogLevel.DEBUG, message, null); }

    private void log(LogLevel level, String message, Throwable t) {
        if (!isLoggable(level)) return;            // before anything is allocated
        dispatch(newRecord(level, message, t));
    }

    private void log(LogLevel level, Supplier<String> message, Throwable t) {
        if (!isLoggable(level)) return;            // message.get() is never called
        dispatch(newRecord(level, message.get(), t));
    }

    private LogRecord newRecord(LogLevel level, String message, Throwable t) {
        // Thread name captured here, on the caller: the writer thread cannot recover
        // it. The clock is injected so tests are deterministic.
        return new LogRecord(clock.instant(), level, name, message,
                Thread.currentThread().getName(), t);
    }

    /** Pipeline, not first match: every appender sees it and none can stop the rest. */
    private void dispatch(LogRecord record) {
        for (Appender appender : appenders) {      // snapshot iteration, no locking
            try {
                appender.append(record);
            } catch (RuntimeException e) {
                System.err.println("appender " + appender.getClass().getSimpleName()
                        + " failed: " + e);
            }
        }
    }
}
import threading
from typing import Callable, Optional, Union
from datetime import datetime

# One parameter type covers both Java overloads: a str, or a callable returning one.
MessageSource = Union[str, Callable[[], str]]


class Logger:
    def __init__(self, name: str, registry: "LoggerRegistry",
                 appenders: list[Appender], clock: Callable[[], datetime]) -> None:
        self._name, self._registry = name, registry
        self._appenders, self._clock = appenders, clock

    def is_loggable(self, level: LogLevel) -> bool:
        return level.is_at_least(self._registry.effective_level(self._name))

    def debug(self, message: MessageSource) -> None:
        self._log(LogLevel.DEBUG, message)

    def info(self, message: MessageSource) -> None:
        self._log(LogLevel.INFO, message)

    def error(self, message: MessageSource,
              throwable: Optional[BaseException] = None) -> None:
        self._log(LogLevel.ERROR, message, throwable)

    def _log(self, level: LogLevel, message: MessageSource,
             throwable: Optional[BaseException] = None) -> None:
        if not self.is_loggable(level):
            return                       # a callable message is never invoked
        record = LogRecord(
            timestamp=self._clock(),
            level=level,
            logger_name=self._name,
            message=message() if callable(message) else message,
            thread_name=threading.current_thread().name,
            throwable=throwable,
        )
        for appender in list(self._appenders):   # pipeline: every appender sees it
            try:
                appender.append(record)
            except Exception as exc:
                print(f"appender {type(appender).__name__} failed: {exc}")
class LoggerRegistry;        // forward declaration, defined with the registry

class Logger {
public:
    Logger(std::string name, LoggerRegistry* registry,
           std::vector<std::shared_ptr<Appender>>* appenders)
        : name_(std::move(name)), registry_(registry), appenders_(appenders) {
    }

    bool isLoggable(LogLevel level) const;        // defined after LoggerRegistry

    void info(const std::string& message) { log(LogLevel::Info, message); }
    void debug(const std::string& message) { log(LogLevel::Debug, message); }

    // The closure overload: the lambda only runs once the guard has passed.
    void debug(const std::function<std::string()>& message) {
        if (!isLoggable(LogLevel::Debug)) return;
        log(LogLevel::Debug, message());
    }

private:
    void log(LogLevel level, const std::string& message) {
        if (!isLoggable(level)) return;
        std::ostringstream threadName;
        threadName << std::this_thread::get_id();
        LogRecord record(std::chrono::system_clock::now(), level, name_,
                         message, threadName.str());
        for (const auto& appender : *appenders_) {
            try {
                appender->append(record);
            } catch (const std::exception& ex) {
                std::cerr << "appender failed: " << ex.what() << "\n";
            }
        }
    }

    std::string name_;
    LoggerRegistry* registry_;
    std::vector<std::shared_ptr<Appender>>* appenders_;
};
class Logger {
    #name;
    #registry;
    #appenders;
    #clock;

    constructor(name, registry, appenders, clock) {
        this.#name = name;
        this.#registry = registry;
        this.#appenders = appenders;     // the registry's shared array
        this.#clock = clock;
    }

    isLoggable(level) {
        return isAtLeast(level, this.#registry.effectiveLevel(this.#name));
    }

    debug(message) { this.#log(LogLevel.DEBUG, message, null); }
    info(message)  { this.#log(LogLevel.INFO, message, null); }
    warn(message)  { this.#log(LogLevel.WARN, message, null); }
    error(message, error = null) { this.#log(LogLevel.ERROR, message, error); }

    // One parameter covers both forms: a string, or a function returning one.
    #log(level, message, error) {
        if (!this.isLoggable(level)) return;     // a function message is not called
        const text = typeof message === "function" ? message() : message;
        const record = new LogRecord(this.#clock(), level, this.#name, text, "main", error);
        for (const appender of this.#appenders) {
            try {
                appender.append(record);
            } catch (err) {
                process.stderr.write(`appender failed: ${err}\n`);
            }
        }
    }
}

LoggerRegistry.java

Where the first-match walk lives. It interns one Logger per name, resolves effective levels by climbing the dotted name, caches the result with a config version stamp, and owns the shared appender list. One line deserves a close read: effectiveLevel reads the version before resolving, because reading it afterwards would let a resolve that raced a setLevel stamp stale data as current – the cache bug that shows up as “changing the level did nothing”.

package logging.core;

import logging.appender.Appender;

import java.time.Clock;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicLong;

public class LoggerRegistry {

    /** The root logger's name. The walk ends here, so the root always has a level. */
    public static final String ROOT = "";

    private final Map<String, LogLevel> configuredLevels = new ConcurrentHashMap<>();
    private final Map<String, CachedLevel> cache = new ConcurrentHashMap<>();
    private final Map<String, Logger> loggers = new ConcurrentHashMap<>();
    private final List<Appender> appenders = new CopyOnWriteArrayList<>();
    private final AtomicLong configVersion = new AtomicLong();
    private final Clock clock;

    public LoggerRegistry(Clock clock) {
        this.clock = clock;
        configuredLevels.put(ROOT, LogLevel.INFO);   // the chain's terminal handler
    }

    /** One Logger per name, created once, so identity is stable for the process. */
    public Logger getLogger(String name) {
        return loggers.computeIfAbsent(name, n -> new Logger(n, this, appenders, clock));
    }

    public void addAppender(Appender appender) { appenders.add(appender); }

    public void setLevel(String name, LogLevel level) {
        configuredLevels.put(name, level);
        configVersion.incrementAndGet();   // every cached entry is now suspect
    }

    /** The first-match walk, cached. com.shop.orders to com.shop to com to root. */
    public LogLevel effectiveLevel(String name) {
        long version = configVersion.get();       // read BEFORE resolving
        CachedLevel hit = cache.get(name);
        if (hit != null && hit.version == version) return hit.level;

        LogLevel resolved = resolve(name);
        cache.put(name, new CachedLevel(resolved, version));
        return resolved;
    }

    /** O(depth) in dotted segments, and only on a cache miss. */
    private LogLevel resolve(String candidate) {
        while (!candidate.isEmpty()) {
            LogLevel configured = configuredLevels.get(candidate);
            if (configured != null) return configured;       // first match wins
            int lastDot = candidate.lastIndexOf('.');
            candidate = lastDot < 0 ? ROOT : candidate.substring(0, lastDot);
        }
        return configuredLevels.get(ROOT);                   // never null
    }

    /** Closes every appender once, which is what drains the async queues. */
    public void close() {
        for (Appender appender : appenders) appender.close();
    }

    private static final class CachedLevel {
        final LogLevel level;
        final long version;

        CachedLevel(LogLevel level, long version) {
            this.level = level;
            this.version = version;
        }
    }

    // ---- the one defensible singleton --------------------------------------
    //
    // A class acquires its logger in a static field, where there is no constructor
    // to inject into:
    //   private static final Logger LOG =
    //       LoggerRegistry.global().getLogger(OrderService.class.getName());
    //
    // The price is shared mutable state across tests: a setLevel in one test is
    // visible in the next unless something resets it. Every class above takes its
    // registry and its Clock as constructor arguments, so tests build their own.
    // global() is a convenience for production call sites, not the design.
    private static final LoggerRegistry GLOBAL = new LoggerRegistry(Clock.systemUTC());

    public static LoggerRegistry global() { return GLOBAL; }
}
import threading
from datetime import datetime, timezone
from typing import Callable, NamedTuple, Optional

ROOT = ""


class _CachedLevel(NamedTuple):
    level: LogLevel
    version: int


class LoggerRegistry:
    def __init__(self, clock: Optional[Callable[[], datetime]] = None) -> None:
        self._clock = clock or (lambda: datetime.now(timezone.utc))
        self._configured: dict[str, LogLevel] = {ROOT: LogLevel.INFO}
        self._cache: dict[str, _CachedLevel] = {}
        self._loggers: dict[str, Logger] = {}
        self._appenders: list[Appender] = []
        self._version = 0
        self._lock = threading.Lock()

    def get_logger(self, name: str) -> Logger:
        with self._lock:
            found = self._loggers.get(name)
            if found is None:
                found = Logger(name, self, self._appenders, self._clock)
                self._loggers[name] = found
            return found

    def add_appender(self, appender: Appender) -> None:
        self._appenders.append(appender)   # readers iterate a copy, so this is safe

    def set_level(self, name: str, level: LogLevel) -> None:
        with self._lock:
            self._configured[name] = level
            self._version += 1             # invalidates every cached entry at once

    def effective_level(self, name: str) -> LogLevel:
        version = self._version            # read before resolving
        hit = self._cache.get(name)
        if hit is not None and hit.version == version:
            return hit.level
        resolved = self._resolve(name)
        self._cache[name] = _CachedLevel(resolved, version)
        return resolved

    def _resolve(self, candidate: str) -> LogLevel:
        while candidate:
            configured = self._configured.get(candidate)
            if configured is not None:
                return configured          # first match wins
            candidate, _, _child = candidate.rpartition(".")
        return self._configured[ROOT]      # the terminal handler, never missing

    def close(self) -> None:
        for appender in list(self._appenders):
            appender.close()


_GLOBAL = LoggerRegistry()     # the one defensible global; tests build their own
class LoggerRegistry {
public:
    static constexpr const char* kRoot = "";

    LoggerRegistry() { configured_[kRoot] = LogLevel::Info; }

    Logger& getLogger(const std::string& name) {
        std::lock_guard<std::mutex> guard(mutex_);
        auto found = loggers_.find(name);
        if (found == loggers_.end()) {
            // unordered_map is node-based, so references survive a rehash.
            found = loggers_.emplace(name, Logger(name, this, &appenders_)).first;
        }
        return found->second;
    }

    void setLevel(const std::string& name, LogLevel level) {
        std::lock_guard<std::mutex> guard(mutex_);
        configured_[name] = level;
        ++version_;                        // invalidates the cache wholesale
    }

    LogLevel effectiveLevel(const std::string& name) {
        std::lock_guard<std::mutex> guard(mutex_);
        const std::size_t version = version_;        // read before resolving
        auto cached = cache_.find(name);
        if (cached != cache_.end() && cached->second.second == version) {
            return cached->second.first;
        }
        const LogLevel resolved = resolveLocked(name);
        cache_[name] = std::make_pair(resolved, version);
        return resolved;
    }

    // addAppender and close mirror the Java tab, both under the same mutex.

private:
    LogLevel resolveLocked(std::string candidate) const {
        while (!candidate.empty()) {
            auto found = configured_.find(candidate);
            if (found != configured_.end()) return found->second;    // first match
            const auto lastDot = candidate.rfind('.');
            candidate = lastDot == std::string::npos
                ? std::string() : candidate.substr(0, lastDot);
        }
        return configured_.at(kRoot);
    }

    std::unordered_map<std::string, LogLevel> configured_;
    std::unordered_map<std::string, std::pair<LogLevel, std::size_t>> cache_;
    std::unordered_map<std::string, Logger> loggers_;
    std::vector<std::shared_ptr<Appender>> appenders_;
    std::size_t version_ = 0;
    mutable std::mutex mutex_;
};

inline bool Logger::isLoggable(LogLevel level) const {
    return isAtLeast(level, registry_->effectiveLevel(name_));
}
const ROOT = "";

class LoggerRegistry {
    #configured = new Map([[ROOT, LogLevel.INFO]]);
    #cache = new Map();
    #loggers = new Map();
    #appenders = [];
    #version = 0;
    #clock;

    constructor(clock = () => new Date()) {
        this.#clock = clock;
    }

    getLogger(name) {
        let found = this.#loggers.get(name);
        if (found === undefined) {
            found = new Logger(name, this, this.#appenders, this.#clock);
            this.#loggers.set(name, found);
        }
        return found;
    }

    addAppender(appender) { this.#appenders.push(appender); }

    setLevel(name, level) {
        this.#configured.set(name, level);
        this.#version++;                       // invalidates every cached entry
    }

    effectiveLevel(name) {
        const version = this.#version;         // read before resolving
        const hit = this.#cache.get(name);
        if (hit !== undefined && hit.version === version) return hit.level;
        const resolved = this.#resolve(name);
        this.#cache.set(name, { level: resolved, version });
        return resolved;
    }

    #resolve(name) {
        let candidate = name;
        while (candidate.length > 0) {
            const configured = this.#configured.get(candidate);
            if (configured !== undefined) return configured;   // first match wins
            const lastDot = candidate.lastIndexOf(".");
            candidate = lastDot < 0 ? ROOT : candidate.slice(0, lastDot);
        }
        return this.#configured.get(ROOT);
    }

    close() {
        for (const appender of this.#appenders) appender.close();
    }
}

const globalRegistry = new LoggerRegistry();   // tests construct their own instead

Demo.java (Runnable end-to-end)

Six labelled scenarios, each printing what it expects before what it got: level filtering suppressing a DEBUG line, hierarchy resolution where configuring com.shop moves com.shop.orders with it, one record reaching two appenders, a lambda whose body is never invoked while the level is off, a bounded queue dropping under load with a non-zero counter, and a shutdown that drains the backlog. The two test doubles are the whole reason Appender is an interface and the Clock is a constructor argument.

package logging;

import logging.appender.Appender;
import logging.appender.AsyncAppender;
import logging.appender.AsyncAppender.OverflowPolicy;
import logging.appender.ConsoleAppender;
import logging.core.LogLevel;
import logging.core.LogRecord;
import logging.core.Logger;
import logging.core.LoggerRegistry;
import logging.format.PatternFormatter;

import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class Demo {

    public static void main(String[] args) {
        // A fixed Clock makes the output reproducible. Nothing reads the wall clock
        // directly, which is the entire reason the Clock is a constructor argument.
        Clock clock = Clock.fixed(Instant.parse("2026-11-12T09:15:00Z"), ZoneOffset.UTC);
        LoggerRegistry registry = new LoggerRegistry(clock);   // injected, not global()

        registry.addAppender(new ConsoleAppender(new PatternFormatter(), LogLevel.INFO));
        CollectingAppender audit = new CollectingAppender(LogLevel.DEBUG);
        registry.addAppender(audit);

        Logger orders = registry.getLogger("com.shop.orders");

        System.out.println("=== 1. Level filter: root is INFO, so DEBUG reaches no appender ===");
        System.out.println("expected: the INFO line prints, the DEBUG record never exists");
        orders.debug("cart rebuilt from 12 line items");
        orders.info("order OD-1001 placed");
        System.out.println("actual:   debug records seen by appenders = "
                + audit.countAtLevel(LogLevel.DEBUG));

        System.out.println();
        System.out.println("=== 2. Hierarchy: configure com.shop, every child follows ===");
        registry.setLevel("com.shop", LogLevel.DEBUG);
        System.out.println("expected: com.shop.orders inherits DEBUG while com.search "
                + "still falls through to the root at INFO");
        System.out.println("actual:   com.shop.orders is "
                + registry.effectiveLevel("com.shop.orders")
                + " and com.search is " + registry.effectiveLevel("com.search"));
        orders.debug("payment gateway latency 41 ms");

        System.out.println();
        System.out.println("=== 3. Fan-out: one call, every appender that passes its floor ===");
        int before = audit.size();
        orders.info("one call, two destinations");
        System.out.println("expected: the console printed it AND the collector grew to "
                + (before + 1));
        System.out.println("actual:   collector size = " + audit.size());

        System.out.println();
        System.out.println("=== 4. The guard: the supplier is not invoked while DEBUG is off ===");
        registry.setLevel("com.shop", LogLevel.INFO);          // DEBUG back off
        AtomicInteger builds = new AtomicInteger();
        orders.debug(() -> expensiveMessage(builds));
        System.out.println("expected: message built 0 times");
        System.out.println("actual:   message built " + builds.get() + " times");
        registry.setLevel("com.shop", LogLevel.DEBUG);         // and on again
        orders.debug(() -> expensiveMessage(builds));
        System.out.println("expected: now built exactly once, so the counter reads 1");
        System.out.println("actual:   message built " + builds.get() + " times");

        System.out.println();
        System.out.println("=== 5. Bounded queue under load: drops counted, ERROR still blocks ===");
        SlowAppender slow = new SlowAppender(LogLevel.DEBUG, 5);
        AsyncAppender async =
                new AsyncAppender(slow, 16, OverflowPolicy.DROP_NEWEST, LogLevel.ERROR);
        LoggerRegistry burstRegistry = new LoggerRegistry(clock);
        burstRegistry.setLevel(LoggerRegistry.ROOT, LogLevel.DEBUG);
        burstRegistry.addAppender(async);
        Logger pricing = burstRegistry.getLogger("com.shop.pricing");

        for (int i = 0; i < 400; i++) pricing.debug("repriced sku-" + i);
        System.out.println("expected: 400 records into a 16-slot queue drained at 5 ms "
                + "each cannot all fit, so dropped is well above zero");
        System.out.println("actual:   dropped = " + async.getDroppedCount()
                + " and queue depth = " + async.getQueueDepth());

        pricing.error("checkout failed for OD-1002",
                new IllegalStateException("gateway timeout"));
        System.out.println("expected: the ERROR blocks the caller rather than being dropped");

        System.out.println();
        System.out.println("=== 6. Shutdown drains the backlog ===");
        System.out.println("expected: close() writes what is still queued, leaving depth 0, "
                + "with the ERROR on the other side");
        async.close();
        System.out.println("actual:   written = " + slow.writtenCount()
                + ", queue depth = " + async.getQueueDepth()
                + ", errors written = " + slow.countAtLevel(LogLevel.ERROR));
        registry.close();
    }

    /** Stands in for the string building a real call site does for free. */
    private static String expensiveMessage(AtomicInteger counter) {
        counter.incrementAndGet();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 500; i++) sb.append("sku-").append(i).append(';');
        return "cart=" + sb;
    }

    /** Test double: keeps records in memory so the demo can assert on them. */
    static final class CollectingAppender implements Appender {
        private final LogLevel threshold;
        private final List<LogRecord> records = new ArrayList<>();

        CollectingAppender(LogLevel threshold) { this.threshold = threshold; }

        @Override
        public synchronized void append(LogRecord record) {
            if (!record.getLevel().isAtLeast(threshold)) return;
            records.add(record);
        }

        @Override public LogLevel getThreshold() { return threshold; }
        @Override public void close() { }

        synchronized int size() { return records.size(); }

        synchronized long countAtLevel(LogLevel level) {
            return records.stream().filter(r -> r.getLevel() == level).count();
        }
    }

    /** Test double: a destination that takes real time, like a disk or a network hop. */
    static final class SlowAppender implements Appender {
        private final LogLevel threshold;
        private final long millisPerWrite;
        private final List<LogRecord> written = new ArrayList<>();

        SlowAppender(LogLevel threshold, long millisPerWrite) {
            this.threshold = threshold;
            this.millisPerWrite = millisPerWrite;
        }

        @Override
        public void append(LogRecord record) {
            if (!record.getLevel().isAtLeast(threshold)) return;
            try {
                Thread.sleep(millisPerWrite);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return;
            }
            synchronized (this) {
                written.add(record);
            }
        }

        @Override public LogLevel getThreshold() { return threshold; }
        @Override public void close() { }

        synchronized int writtenCount() { return written.size(); }

        synchronized long countAtLevel(LogLevel level) {
            return written.stream().filter(r -> r.getLevel() == level).count();
        }
    }
}
import time
from datetime import datetime, timezone

FIXED_NOW = datetime(2026, 11, 12, 9, 15, tzinfo=timezone.utc)

# CollectingAppender keeps records in a list; SlowAppender sleeps before recording.
# Both are four-line Appender subclasses, exactly as in the Java tab.


def main() -> None:
    registry = LoggerRegistry(clock=lambda: FIXED_NOW)
    registry.add_appender(ConsoleAppender(PatternFormatter(), LogLevel.INFO))
    audit = CollectingAppender(LogLevel.DEBUG)
    registry.add_appender(audit)
    orders = registry.get_logger("com.shop.orders")

    print("=== 1. Level filter: root is INFO, so DEBUG reaches no appender ===")
    orders.debug("cart rebuilt from 12 line items")
    orders.info("order OD-1001 placed")
    debugs = sum(1 for r in audit.records if r.level is LogLevel.DEBUG)
    print(f"expected: 0 debug records seen | actual: {debugs}")

    print("\n=== 2. Hierarchy: configure com.shop, every child follows ===")
    registry.set_level("com.shop", LogLevel.DEBUG)
    print("expected: com.shop.orders DEBUG by inheritance, com.search INFO from root")
    print(f"actual:   {registry.effective_level('com.shop.orders').name} and "
          f"{registry.effective_level('com.search').name}")

    print("\n=== 3. Fan-out: one call, every appender that passes its floor ===")
    before = len(audit.records)
    orders.info("one call, two destinations")
    print(f"expected: collector grows to {before + 1} | actual: {len(audit.records)}")

    print("\n=== 4. The guard: the callable is not invoked while DEBUG is off ===")
    registry.set_level("com.shop", LogLevel.INFO)
    builds = []

    def expensive() -> str:
        builds.append(1)
        return "cart=" + ";".join(f"sku-{i}" for i in range(500))

    orders.debug(expensive)
    print(f"expected: built 0 times | actual: {len(builds)}")
    registry.set_level("com.shop", LogLevel.DEBUG)
    orders.debug(expensive)
    print(f"expected: built exactly once | actual: {len(builds)}")

    print("\n=== 5. Bounded queue under load, then 6. a draining close ===")
    slow = SlowAppender(LogLevel.DEBUG, 0.005)
    writer = AsyncAppender(slow, 16, "drop_newest", LogLevel.ERROR)
    burst = LoggerRegistry(clock=lambda: FIXED_NOW)
    burst.set_level(ROOT, LogLevel.DEBUG)
    burst.add_appender(writer)
    pricing = burst.get_logger("com.shop.pricing")

    for i in range(400):
        pricing.debug(f"repriced sku-{i}")
    print("expected: 400 records into a 16-slot queue drained at 5 ms each cannot fit, "
          "so dropped is well above zero")
    print(f"actual:   dropped = {writer.dropped_count}, depth = {writer.queue_depth}")

    pricing.error("checkout failed for OD-1002", RuntimeError("gateway timeout"))
    print("expected: the ERROR blocks rather than dropping, and close drains the rest")
    writer.close()
    errors = sum(1 for r in slow.written if r.level is LogLevel.ERROR)
    print(f"actual:   written = {len(slow.written)}, depth = {writer.queue_depth}, "
          f"errors written = {errors}")
    registry.close()


if __name__ == "__main__":
    main()
#include <iostream>
#include <memory>
#include "AsyncAppender.h"
#include "LoggerRegistry.h"

// CollectingAppender and SlowAppender are as in the Java tab: one records into a
// vector, the other sleeps before recording, both guarded by their own mutex.

int main() {
    LoggerRegistry registry;
    auto formatter = std::make_shared<PatternFormatter>();
    registry.addAppender(std::make_shared<ConsoleAppender>(formatter, LogLevel::Info));
    Logger& orders = registry.getLogger("com.shop.orders");

    std::cout << "=== 1. Level filter: root is INFO, DEBUG is suppressed ===\n";
    orders.debug("cart rebuilt from 12 line items");      // nothing is emitted
    orders.info("order OD-1001 placed");

    std::cout << "\n=== 2. Hierarchy: configure com.shop, every child follows ===\n"
              << "expected: com.shop.orders DEBUG, com.search INFO\n"
              << "actual:   ";
    registry.setLevel("com.shop", LogLevel::Debug);
    std::cout << levelName(registry.effectiveLevel("com.shop.orders")) << " and "
              << levelName(registry.effectiveLevel("com.search")) << "\n";

    std::cout << "\n=== 3. The guard: the lambda is not invoked while DEBUG is off ===\n";
    registry.setLevel("com.shop", LogLevel::Info);
    int builds = 0;
    orders.debug([&builds]() -> std::string {
        ++builds;
        return "cart=large";
    });
    std::cout << "expected: built 0 times | actual: " << builds << "\n";

    std::cout << "\n=== 4. Bounded queue under load, then a draining close ===\n";
    auto slow = std::make_shared<SlowAppender>(LogLevel::Debug, 5);
    auto writer = std::make_shared<AsyncAppender>(
        slow, 16, AsyncAppender::OverflowPolicy::DropNewest, LogLevel::Error);

    LoggerRegistry burst;
    burst.setLevel(LoggerRegistry::kRoot, LogLevel::Debug);
    burst.addAppender(writer);
    Logger& pricing = burst.getLogger("com.shop.pricing");

    for (int i = 0; i < 400; ++i) pricing.debug("repriced sku-" + std::to_string(i));
    std::cout << "expected: dropped well above zero | actual: "
              << writer->droppedCount() << "\n";

    pricing.error("checkout failed for OD-1002");
    std::cout << "expected: the ERROR waits for a slot rather than being dropped\n";
    writer->close();                                      // drains the backlog
    std::cout << "actual:   written = " << slow->writtenCount() << "\n";
    registry.close();
    return 0;
}
const FIXED_NOW = new Date("2026-11-12T09:15:00Z");

// CollectingAppender pushes records onto an array. BusyAppender spins for a few
// milliseconds first, standing in for a slow write. Both are as in the Java tab.

function main() {
    const registry = new LoggerRegistry(() => FIXED_NOW);
    registry.addAppender(new ConsoleAppender(new PatternFormatter(), LogLevel.INFO));
    const audit = new CollectingAppender(LogLevel.DEBUG);
    registry.addAppender(audit);
    const orders = registry.getLogger("com.shop.orders");

    console.log("=== 1. Level filter: root is INFO, so DEBUG reaches no appender ===");
    orders.debug("cart rebuilt from 12 line items");
    orders.info("order OD-1001 placed");
    const debugs = audit.records.filter((r) => r.level === LogLevel.DEBUG).length;
    console.log(`expected: 0 debug records seen | actual: ${debugs}`);

    console.log("\n=== 2. Hierarchy: configure com.shop, every child follows ===");
    registry.setLevel("com.shop", LogLevel.DEBUG);
    console.log("expected: com.shop.orders DEBUG by inheritance, com.search INFO");
    console.log(`actual:   ${registry.effectiveLevel("com.shop.orders").name} and `
        + `${registry.effectiveLevel("com.search").name}`);

    console.log("\n=== 3. Fan-out: one call, every appender that passes its floor ===");
    const before = audit.records.length;
    orders.info("one call, two destinations");
    console.log(`expected: collector grows to ${before + 1}`
        + ` | actual: ${audit.records.length}`);

    console.log("\n=== 4. The guard: the function is not called while DEBUG is off ===");
    registry.setLevel("com.shop", LogLevel.INFO);
    let builds = 0;
    const expensive = () => {
        builds++;
        return "cart=" + Array.from({ length: 500 }, (_, i) => `sku-${i}`).join(";");
    };
    orders.debug(expensive);
    console.log(`expected: built 0 times | actual: ${builds}`);
    registry.setLevel("com.shop", LogLevel.DEBUG);
    orders.debug(expensive);
    console.log(`expected: built exactly once | actual: ${builds}`);

    console.log("\n=== 5. Bounded buffer under load, then 6. a draining close ===");
    const busy = new BusyAppender(LogLevel.DEBUG, 2);
    const writer = new AsyncAppender(busy, 16, "drop_newest", LogLevel.ERROR);
    const burst = new LoggerRegistry(() => FIXED_NOW);
    burst.setLevel("", LogLevel.DEBUG);
    burst.addAppender(writer);
    const pricing = burst.getLogger("com.shop.pricing");

    for (let i = 0; i < 400; i++) pricing.debug(`repriced sku-${i}`);
    console.log("expected: a 16-slot buffer cannot hold 400 records before the drain "
        + "runs, so dropped is well above zero");
    console.log(`actual:   dropped = ${writer.droppedCount}, depth = ${writer.queueDepth}`);

    pricing.error("checkout failed for OD-1002", new Error("gateway timeout"));
    console.log("expected: the ERROR is written inline rather than dropped");
    writer.close();
    console.log(`actual:   written = ${busy.written.length}, depth = ${writer.queueDepth}`);
    registry.close();
}

main();

Sequence Diagram – One DEBUG call, the guard, the fan-out and a full queue

💡 A sequence diagram reads top to bottom as time passing. Each vertical line is one object or thread staying alive, each horizontal arrow is one call, and the alt block is a branch where only one path runs. The writer thread’s lifeline is independent: it is still draining after the caller has returned.

sequenceDiagram
    participant App as Caller thread
    participant L as Logger
    participant R as LoggerRegistry
    participant A as AsyncAppender
    participant Q as ArrayBlockingQueue
    participant W as Writer thread
    participant F as FileAppender

    App->>L: debug with a supplier
    L->>R: effectiveLevel of com.shop.orders
    R->>R: cache miss so walk com.shop then com then root
    R-->>L: DEBUG inherited from com.shop
    L->>L: guard passes so invoke the supplier
    L->>A: append the record
    A->>Q: offer the record
    alt a slot is free
        Q-->>A: accepted
        A-->>L: returns with no I O done
    else queue full and level below ERROR
        Q-->>A: rejected
        A->>A: dropped counter plus one
        A-->>L: returns having written nothing
    end
    L-->>App: returns
    W->>Q: take blocks until a record arrives
    Q-->>W: the record
    W->>F: append the record
    F->>F: format then write and flush if ERROR

How to Extend

Extension Implementation
A new destination: syslog, Kafka, an HTTP collector A new class implementing Appender; AppenderFactory gains one branch and nothing else changes
Rolling files by size or date RollingFileAppender implements Appender, owning its own rename-and-reopen; the decorators above it are untouched
Request context: requestId, userId A ThreadLocal map read in Logger.newRecord and carried as a field on LogRecord. It has to be copied at creation, because the writer thread cannot see the caller’s ThreadLocal
Sampling or rate limiting a noisy logger ThrottlingAppender implements Appender, wrapping the real one and holding a token bucket or a one-in-N counter – another decorator, exactly the mechanism in Rate Limiter
Per-logger appenders with additivity Logger keeps its own list and dispatch walks ancestors through the registry, which turns the fan-out into a second hierarchy walk
Never losing a record the file rejects FileAppender’s catch block hands the record to a fallback appender instead of stderr, which is a dead-letter queue in miniature
Reloadable config Watch the config file, rebuild the stack with AppenderFactory, swap the list and close() the old stack; setLevel already invalidates the cache by version

What Interviewers Look For

  1. ✅ The guard runs before the message exists – isLoggable is checked at the top of log and there is a Supplier overload, because log.debug("cart=" + cart) otherwise pays full price with debug off.
  2. ✅ The two chains are named correctly – level resolution is a first-match walk up the dotted name, the appender list is a pipeline where nothing short-circuits, and the candidate can say which is which and what breaks if you swap them.
  3. ✅ No I/O on the caller’s thread – the hot path is one offer, while formatting and writing belong to the writer thread, which only works because LogRecord is immutable and self-contained.
  4. ✅ The queue is bounded and the policy is explicit – a chosen tradeoff between blocking, dropping newest and dropping oldest, ideally keyed off the level, rather than an unbounded queue that turns a slow disk into an OutOfMemoryError.
  5. ✅ Drops are counted and exported – an AtomicLong behind a metric, so a hole in the log file is explainable, and nobody tries to log the fact that logging failed.
  6. ✅ close() actually drains – a sentinel ordered behind the backlog, a bounded join, the delegate closed so the file handle flushes, and the leftover depth reported when the join times out.
  7. ✅ The logger never throws into business code – an appender failure goes to a side channel and the loop continues, and one poisonous record cannot kill the writer thread and silently end logging for the process.
  8. ✅ Testability was designed in rather than bolted on – an injected Clock, destinations behind an interface so a collecting double works, and a registry you can construct per test instead of only reaching through global().

  • Pub/Sub System – the same bounded-queue and slow-consumer problem, except the overflow policy there has to survive several independent subscribers
  • Notification Service – a first-match chain for real: channels tried in order until one delivers, which is the opposite of the appender fan-out
  • Task Scheduler – the worker-thread-plus-queue skeleton again, with the queue ordered by time instead of by arrival
  • Rate Limiter – what a ThrottlingAppender wraps when one noisy logger is the thing saturating the writer

Scale this design past a single process and these are the concepts it runs into:

  • Backpressure → – the overflow policy is backpressure, and shipping logs to a central collector pushes the same decision one hop out, where the queue is a socket buffer you do not own
  • Observability → – dropped records, queue depth and writer latency are metrics rather than log lines, and a logging framework that cannot report its own loss is lying by omission
  • Dead-letter queue → – records the collector rejects need somewhere to go, which is the same side channel the FileAppender catch block wants