A logger is the one piece of code that runs inside every request of every other system. That changes what “good design” means for it. A parking lot that is a bit slow is a slow parking lot. A logger that is a bit slow makes checkout slow, and a logger that throws when the disk fills up turns a full disk into an outage. So most of the interesting questions here are about what the logger does when things go wrong: a sink that cannot keep up, a sink that fails, two threads writing at once, a user who types a newline into a login form.
The class structure is small and well known, because every serious library (log4j, logback, Python’s logging) converged on it: loggers, levels, appenders, formatters. You get credit for knowing that shape, and you earn the rest by defending what happens under load.
The code is about 670 lines of Python and 590 of Java, both including a benchmark mode. The demos print the same bytes in both languages.
Agree the scope in the first five minutes
| In | Out, and say so |
|---|---|
| Levels DEBUG, INFO, WARN, ERROR; a message is written only if its level is at or above the threshold | Configuration files and hot reload (an extension below) |
Named loggers in a tree (app.db.pool under app.db), with levels inherited and changeable at runtime | Shipping logs over the network to a central store; that is a separate service |
| Several sinks per logger (console, file, an in-memory list for tests), each with its own minimum level and format | Exceptions with stack traces; one more field on the record, nothing new in the design |
| Plain-text and JSON formats; per-request context such as a request id | Searching or querying logs |
| A rolling file: start a new file past a size limit, keep N old ones | Time-based rotation and compression of old files |
| An async mode so a slow sink does not slow the caller, with a stated policy for when the queue is full | Guaranteed delivery across a crash |
| Safe to call from many threads; a failing sink never throws into the caller | Multiple processes writing one file |
The last row of the “In” column is the one to say out loud. Logging is best-effort by design. If an interviewer wants “never lose a log line”, that is an audit log, and it belongs in a database transaction, not in a logging framework.
The pipeline, then the classes
Every call goes through the same five steps:
log.info("GET /cart 200 in {} ms", 38)on aLogger.- Level check. If INFO is below the logger’s effective level, return. Nothing has been formatted yet, and nothing allocated beyond the argument array.
- Build a
Record: time, level, logger name, thread name, the rendered message, a copy of the thread’s context. All of it on the calling thread, at the moment of the call. - Hand the record to every appender on this logger, then on its parent, up to the root, unless a logger has
propagateswitched off. - Each appender checks its own threshold, asks its formatter for a line, and writes the whole line while holding its own lock.
The classes fall out of that:
Level: an ordered enum. The numbers (10, 20, 30, 40) leave room to add TRACE or FATAL later without renumbering.Logger: a name, an optional level, a parent, a list of appenders, a propagate flag.LogManager: owns the tree, creates loggers by name, creates missing parents, holds the clock.Record: an immutable value. Once built, nothing changes it.Formatter: one method,format(record) → str.PlainFormatterandJsonFormatter.Appender: threshold, formatter, lock, andwrite(line).ConsoleAppender,ListAppender,RollingFileAppender, andAsyncAppender, which wraps another appender.Context: a thread-local map for things like the request id (log4j and logback call it the MDC).
classDiagram
class LogManager {
+root: Logger
+clock()
+get(name) Logger
+shutdown()
}
class Logger {
+name: str
+level: Level or null
+propagate: bool
+effective_level() Level
+log(level, msg, args)
+info(msg, args)
+error(msg, args)
}
class Level {
<<enumeration>>
DEBUG 10
INFO 20
WARN 30
ERROR 40
}
class Record {
+time_ms: int
+level: Level
+logger: str
+thread: str
+msg: str
+ctx: map
}
class Appender {
<<abstract>>
+threshold: Level
-lock
+append(record)
#write(line)
+close()
}
class Formatter {
<<interface>>
+format(record) str
}
class AsyncAppender {
+capacity: int
+dropped: int
+evicted: int
+flush()
}
class Context {
+put(key, value)
+snapshot() map
}
LogManager "1" *-- "*" Logger
Logger --> "0..1" Logger : parent
Logger "1" o-- "*" Appender
Logger ..> Record : creates
Logger ..> Context : snapshots
Record --> Level
Appender --> Formatter
Formatter <|.. PlainFormatter
Formatter <|.. JsonFormatter
Appender <|-- ConsoleAppender
Appender <|-- ListAppender
Appender <|-- RollingFileAppender
Appender <|-- AsyncAppender
AsyncAppender o-- "1" Appender : targetTwo thresholds, and why loggers form a tree
There are two level checks, and candidates often merge them into one. The logger’s level answers “does anyone care about DEBUG from app.db right now?” The appender’s threshold answers “does this sink want it?” You need both: the console shows INFO and above, the alerting sink only WARN and above, and turning on DEBUG for the database code during an incident should not turn it on for the HTTP layer.
That last sentence is why loggers have dotted names and parents. app.db.pool has no level of its own; it inherits from app.db, which inherits from the root. Set app.db to DEBUG and the whole database subtree gets louder, nothing else does.
The effective level is computed by walking up the parent chain on every call. That is three or four pointer hops, and it means a level change at runtime takes effect immediately for every child. The tempting optimisation is to copy the effective level into each logger when it is created. Then the on-call engineer sets app.db to DEBUG at 2 a.m., and app.db.pool, created at startup, stays at INFO. logback does cache the effective level in each logger, but it also pushes every level change down to the children. If you cache, you own that invalidation.
Formatting: when, and on which thread
Three decisions, each with a bug behind it.
Check the level before building the string. log.debug(f"order {order}") builds the string, and calls order.__str__(), even when DEBUG is off. log.debug("order {}", order) passes the object and the logger renders it only after the level check. With a toString that joins 100 line items, a million disabled calls took 723 ms with concatenation and 9 ms with a placeholder in Java, 1.05 s against 0.20 s in Python (numbers further down). In hot paths, Python code often wraps the call in if log.is_enabled(DEBUG):, which brought it down to 0.08 s, because Python pays for the method call and the argument tuple even when the level is off.
Render the message on the calling thread, not later. If the async worker did the formatting, a caller that logs a list and then appends to it would see the appended version in the log, written a few milliseconds later from a different thread. The same goes for the thread name and the request id: capture them when the record is built. Demo 7 shows the payoff: the async worker thread is called log-async, but every line says [producer] and carries req=r-77, because that is who logged it.
Escape newlines in the plain format. A username of bob\n10:17:00.007 INFO [main] app.auth - admin login ok will otherwise produce a perfectly forged second log line. The plain formatter writes \n as the two characters \ and n. JSON escaping does this for free, which is one of several reasons to log JSON in production.
Observer, chain of responsibility, and the singleton question
Observer, for appenders. A logger keeps a list of appenders and gives each record to all of them. That is the Observer shape: the logger does not know what a file or a console is. Adding a Kafka sink is a new class and one line of configuration.
Strategy, for formatters. The same file appender can write plain text on a developer’s laptop and JSON in production.
Decorator, for async. AsyncAppender is an Appender that wraps another one. Any sink becomes asynchronous without the sink knowing, and tests can use the synchronous one directly.
Template method, inside Appender.append. The base class does the threshold check, formats outside the lock, takes the lock, and calls write(line). Subclasses only write. That is how every sink gets “whole lines, never interleaved” without each author remembering to lock.
Chain of responsibility: the textbook version, rejected. A lot of written answers to this question build DebugLogger → InfoLogger → ErrorLogger, where each handler deals with its own level and passes the message on. It encodes levels as classes, so a new level means a new class and re-linking the chain. Worse, it mixes “how important is this message” with “where does it go”. A single ERROR has to reach the console, the file and the alerting sink, which is fan-out, not “the first handler that can deal with it”. The walk from app.db.pool up to the root does look like a chain, and you can call it that, but every node both handles and passes on, and the only thing that stops it is propagate = false.
Singleton: a default instance, not a hidden one. Logging is the one place where a global is defensible. Code all over the codebase writes private static final Logger log = LoggerFactory.getLogger(Foo.class), and nobody is going to inject a logger into every class. So there is a module-level get_logger(name) backed by one lazily created LogManager (a holder class in Java, double-checked locking in Python). But LogManager itself is an ordinary class with a constructor that takes a clock. Every demo below builds its own, which is why eight demos with different configurations do not interfere. Make the manager a true singleton with a private constructor and your tests share one global tree, and the test that sets app.db to DEBUG changes the output of every test after it.
Also turned down:
- A builder for records. A record has six fields, all required, built in one place.
- Inheritance for JSON vs plain file appenders (
JsonFileAppender extends FileAppender). Format and destination vary independently; two hierarchies multiply into four classes, then six. - A generic event bus. Observer with one producer and a fixed list of consumers does not need a bus, topics or subscriptions.
When the queue is full
The async appender is a bounded queue and one worker thread. The caller’s cost becomes “take a lock, append to a deque”, about 0.5 µs in Java against 200 µs for the slow sink in the benchmark. The design question is what happens when the worker falls behind and the queue fills up. There are three honest answers:
- Block the caller. Nothing is lost, and a slow disk now slows every request. This is how you turn a logging problem into an outage.
- Drop the new record. Requests never wait, and when the disk is slow you lose exactly the ERROR lines you will want in the postmortem.
- Drop by level. What this design does. A record below WARN is dropped when the queue is full. A WARN or ERROR evicts the oldest record below WARN. Only when the queue holds nothing but WARN and ERROR does the caller wait. logback’s
AsyncAppenderdoes something similar: by default, once the queue is 80% full it discards TRACE, DEBUG and INFO events.
Whatever you choose, count what you drop and expose the counter. “We lost 191 INFO lines in the last minute” is a metric; silently losing them is a mystery.
close() matters more than it looks. The worker is a daemon thread, so if the program exits without closing the appender, whatever is still in the queue is gone, usually the last few lines before a crash. LogManager.shutdown() closes every appender, and the async one drains its queue before returning. Register it as a shutdown hook.
Whole lines or nothing
Each appender writes a complete line under its own lock. To see what the lock buys, the benchmark has a file appender that writes the text and the newline as two write() calls (exactly what a print(msg); print("\n")-style sink does), with four threads writing 50,000 lines each. Without the lock, Java produced 108,984 malformed lines out of 200,000, more than half. Python produced 3,361: the GIL hides most of the interleaving, which is how this bug survives local testing and then shows up in production. With the lock, 0 in both.
One lock per appender, not one for the whole framework. A slow file appender should not make the console wait. And formatting happens before the lock is taken, so the lock covers only the write.
The code
Both files were run on the box this lesson was written on (Python 3.13.5, OpenJDK 21.0.13, 8 vCPUs). The default run prints byte-for-byte the same output in both languages; I ran each five times and compared. Demos use a fake clock that advances a fixed number of milliseconds per record, which is why the timestamps are reproducible. --bench prints timings, which will differ on your machine. Files, expected-output.txt and bench-output.txt are in course-code/low-level-design/18/ in the course repository.
Before reading:
Logger.logis the hot path. The level check is the first line, and the record is built only after it.Appender.appendis the template: threshold, format, lock,write. Subclasses overridewriteonly, except the async and test appenders, which overrideappendbecause they hand the record on instead of writing a line.AsyncAppender.appendcontains the whole full-queue policy in about fifteen lines.- The demo for the async appender uses a
GateAppenderthat blocks inside its first write until released. It freezes the worker so the full-queue behaviour is deterministic instead of depending on thread timing.
Python
"""Logging framework: levels, a tree of named loggers, appenders that each have
their own threshold and formatter, per-thread context, a size-based rolling file,
and an async appender with a bounded queue that drops INFO before it drops ERROR.
Run: python3 logger.py deterministic demos (same output as Logger.java)
python3 logger.py --bench timings, which depend on the machine
"""
from __future__ import annotations
import os
import sys
import tempfile
import threading
import time
from collections import deque
from enum import IntEnum
class Level(IntEnum):
DEBUG = 10
INFO = 20
WARN = 30
ERROR = 40
OFF = 100
def render(msg: str, args: tuple) -> str:
"""SLF4J-style '{}' placeholders. Only called once the level is known to be on."""
if not args:
return msg
out, i, a = [], 0, 0
while True:
j = msg.find("{}", i)
if j < 0 or a == len(args):
out.append(msg[i:])
return "".join(out)
out.append(msg[i:j])
out.append(str(args[a]))
a += 1
i = j + 2
# ---------------- per-thread context (MDC) ----------------
class Context:
_local = threading.local()
@classmethod
def _map(cls) -> dict:
if not hasattr(cls._local, "m"):
cls._local.m = {}
return cls._local.m
@classmethod
def put(cls, key: str, value: str) -> None:
cls._map()[key] = value
@classmethod
def clear(cls) -> None:
cls._map().clear()
@classmethod
def snapshot(cls) -> dict:
return dict(cls._map())
class Record:
"""Everything is captured on the calling thread, at the moment of the call."""
__slots__ = ("time_ms", "level", "logger", "thread", "msg", "ctx")
def __init__(self, time_ms, level, logger, thread, msg, ctx):
self.time_ms, self.level, self.logger = time_ms, level, logger
self.thread, self.msg, self.ctx = thread, msg, ctx
# ---------------- formatters ----------------
def clock_text(ms: int) -> str:
ms %= 86_400_000
return f"{ms // 3_600_000:02d}:{ms // 60_000 % 60:02d}:{ms // 1000 % 60:02d}.{ms % 1000:03d}"
def escape_line(s: str) -> str:
return s.replace("\\", "\\\\").replace("\n", "\\n").replace("\r", "\\r")
def json_str(s: str) -> str:
out = ['"']
for ch in s:
if ch == '"':
out.append('\\"')
elif ch == "\\":
out.append("\\\\")
elif ch == "\n":
out.append("\\n")
elif ch == "\r":
out.append("\\r")
elif ch == "\t":
out.append("\\t")
elif ord(ch) < 0x20:
out.append(f"\\u{ord(ch):04x}")
else:
out.append(ch)
out.append('"')
return "".join(out)
class PlainFormatter:
def format(self, r: Record) -> str:
line = f"{clock_text(r.time_ms)} {r.level.name:<5} [{r.thread}] {r.logger} - {escape_line(r.msg)}"
if r.ctx:
line += " {" + ", ".join(f"{k}={v}" for k, v in r.ctx.items()) + "}"
return line
class JsonFormatter:
def format(self, r: Record) -> str:
parts = [
f'"time":{json_str(clock_text(r.time_ms))}',
f'"level":{json_str(r.level.name)}',
f'"logger":{json_str(r.logger)}',
f'"thread":{json_str(r.thread)}',
f'"msg":{json_str(r.msg)}',
]
if r.ctx:
parts.append('"ctx":{' + ",".join(f"{json_str(k)}:{json_str(v)}" for k, v in r.ctx.items()) + "}")
return "{" + ",".join(parts) + "}"
# ---------------- appenders ----------------
class Appender:
"""Filter by threshold, format outside the lock, write one whole line under it."""
def __init__(self, formatter=None, threshold: Level = Level.DEBUG):
self.formatter = formatter or PlainFormatter()
self.threshold = threshold
self._lock = threading.Lock()
def append(self, r: Record) -> None:
if r.level < self.threshold:
return
line = self.formatter.format(r)
with self._lock:
self.write(line)
def write(self, line: str) -> None:
raise NotImplementedError
def close(self) -> None:
pass
class ConsoleAppender(Appender):
def write(self, line: str) -> None:
print(" " + line)
class ListAppender(Appender):
def __init__(self, formatter=None, threshold: Level = Level.DEBUG):
super().__init__(formatter, threshold)
self.lines: list[str] = []
def write(self, line: str) -> None:
self.lines.append(line)
class BrokenAppender(Appender):
def write(self, line: str) -> None:
raise OSError("disk full")
class RollingFileAppender(Appender):
"""app.log is current; app.log.1 the previous file, up to app.log.<backups>."""
def __init__(self, path, max_bytes, backups, formatter=None, threshold=Level.DEBUG):
super().__init__(formatter, threshold)
self.path, self.max_bytes, self.backups = path, max_bytes, backups
self._f = open(path, "ab")
self._size = self._f.tell()
def write(self, line: str) -> None:
data = (line + "\n").encode("utf-8")
if self._size > 0 and self._size + len(data) > self.max_bytes:
self._roll()
self._f.write(data)
self._f.flush()
self._size += len(data)
def _roll(self) -> None:
self._f.close()
oldest = f"{self.path}.{self.backups}"
if os.path.exists(oldest):
os.remove(oldest)
for i in range(self.backups - 1, 0, -1):
if os.path.exists(f"{self.path}.{i}"):
os.replace(f"{self.path}.{i}", f"{self.path}.{i + 1}")
os.replace(self.path, f"{self.path}.1")
self._f = open(self.path, "ab")
self._size = 0
def close(self) -> None:
with self._lock:
self._f.close()
class AsyncAppender(Appender):
"""Decorator: the caller only enqueues; one worker thread writes to `target`.
When the queue is full: a record below WARN is dropped; a WARN or ERROR evicts
the oldest record below WARN; if the queue holds nothing but WARN/ERROR, the
caller waits. Errors are never lost, and INFO never makes a request wait.
"""
def __init__(self, target: Appender, capacity: int = 8192):
super().__init__(None, Level.DEBUG)
self.target, self.capacity = target, capacity
self._q: deque[Record] = deque()
self._cv = threading.Condition()
self._pending = 0 # queued + being written
self._closed = False
self.dropped = 0
self.evicted = 0
self._worker = threading.Thread(target=self._run, name="log-async", daemon=True)
self._worker.start()
def append(self, r: Record) -> None:
with self._cv:
if self._closed:
self.target.append(r) # late shutdown messages: write directly
return
while len(self._q) >= self.capacity:
if r.level < Level.WARN:
self.dropped += 1
return
victim = next((x for x in self._q if x.level < Level.WARN), None)
if victim is not None:
self._q.remove(victim)
self.evicted += 1
self._pending -= 1
break
self._cv.wait()
self._q.append(r)
self._pending += 1
self._cv.notify_all()
def _run(self) -> None:
while True:
with self._cv:
while not self._q and not self._closed:
self._cv.wait()
if not self._q:
return
r = self._q.popleft()
self._cv.notify_all()
try:
self.target.append(r)
except Exception as e: # the worker must survive a bad write
print(f"log-async: {e}", file=sys.stderr)
with self._cv:
self._pending -= 1
self._cv.notify_all()
def flush(self) -> None:
with self._cv:
while self._pending:
self._cv.wait()
def close(self) -> None:
with self._cv:
self._closed = True
self._cv.notify_all()
self._worker.join()
self.target.close()
# ---------------- loggers ----------------
class Logger:
def __init__(self, name: str, parent: Logger | None, manager: LogManager):
self.name, self.parent, self.manager = name, parent, manager
self.level: Level | None = None # None = inherit from parent
self.appenders: list[Appender] = []
self.propagate = True
def effective_level(self) -> Level:
lg = self
while lg.level is None:
lg = lg.parent
return lg.level
def is_enabled(self, level: Level) -> bool:
return level >= self.effective_level()
def log(self, level: Level, msg: str, *args) -> None:
if level < self.effective_level():
return # nothing formatted, nothing allocated
r = Record(self.manager.clock(), level, self.name,
threading.current_thread().name, render(msg, args), Context.snapshot())
lg = self
while lg is not None:
for a in lg.appenders:
try:
a.append(r)
except Exception as e: # a broken sink must not break the request
self.manager.report_failure(a, e)
if not lg.propagate:
break
lg = lg.parent
def debug(self, msg, *args): self.log(Level.DEBUG, msg, *args)
def info(self, msg, *args): self.log(Level.INFO, msg, *args)
def warn(self, msg, *args): self.log(Level.WARN, msg, *args)
def error(self, msg, *args): self.log(Level.ERROR, msg, *args)
class LogManager:
"""Owns the logger tree. One default instance for the app, fresh ones for tests."""
def __init__(self, clock=None):
self.clock = clock or (lambda: int(time.time() * 1000))
self.root = Logger("root", None, self)
self.root.level = Level.INFO
self._loggers: dict[str, Logger] = {}
self._lock = threading.Lock()
self.failures = 0
self.last_failure = ""
def get(self, name: str) -> Logger:
with self._lock:
lg = self._loggers.get(name)
if lg is None:
dot = name.rfind(".")
parent = self.root if dot < 0 else self._get_locked(name[:dot])
lg = self._loggers[name] = Logger(name, parent, self)
return lg
def _get_locked(self, name: str) -> Logger:
lg = self._loggers.get(name)
if lg is None:
dot = name.rfind(".")
parent = self.root if dot < 0 else self._get_locked(name[:dot])
lg = self._loggers[name] = Logger(name, parent, self)
return lg
def report_failure(self, appender: Appender, e: Exception) -> None:
with self._lock:
self.failures += 1
self.last_failure = f"{type(appender).__name__}: {e}"
def shutdown(self) -> None:
seen = []
for lg in [self.root, *self._loggers.values()]:
for a in lg.appenders:
if a not in seen:
seen.append(a)
a.close()
_default: LogManager | None = None
_default_lock = threading.Lock()
def get_logger(name: str) -> Logger:
global _default
if _default is None:
with _default_lock:
if _default is None:
_default = LogManager()
return _default.get(name)
class FakeClock:
def __init__(self, start_ms: int, step_ms: int):
self.now, self.step, self._lock = start_ms, step_ms, threading.Lock()
def __call__(self) -> int:
with self._lock:
t = self.now
self.now += self.step
return t
# ---------------- demos ----------------
class Expensive:
calls = 0
def __str__(self):
Expensive.calls += 1
return "Order(id=9, items=3)"
class BigOrder:
"""A toString that does real work: 100 line items, like dumping a request body."""
def __init__(self):
self.items = [f"sku-{i}:{i % 7 + 1}" for i in range(100)]
def __str__(self):
return "Order[" + ", ".join(self.items) + "]"
class GateAppender(Appender):
"""Blocks inside the first write until released, to freeze the async worker."""
def __init__(self, target: Appender):
super().__init__(None, Level.DEBUG)
self.target = target
self.entered = threading.Event()
self.release = threading.Event()
def append(self, r: Record) -> None:
self.entered.set()
self.release.wait()
self.target.append(r)
def demo_levels():
print("1) Levels and the logger tree (root INFO, app.db DEBUG)")
m = LogManager(FakeClock(36_900_000, 7))
m.root.appenders.append(ConsoleAppender())
m.get("app.db").level = Level.DEBUG
http, db, pool = m.get("app.http"), m.get("app.db"), m.get("app.db.pool")
http.debug("GET /cart headers={}", 14)
http.info("GET /cart 200 in {} ms", 38)
db.debug("SELECT took {} ms", 4)
pool.debug("borrowed connection {} of {}", 7, 20)
print(" -- set app.db to WARN at runtime")
db.level = Level.WARN
pool.debug("borrowed connection {} of {}", 8, 20)
pool.warn("pool exhausted, waited {} ms", 250)
print(f" effective level of app.db.pool: {pool.effective_level().name}, of app.http: {http.effective_level().name}")
def demo_sinks():
print("\n2) Two sinks: console (plain, INFO+) and alerts (JSON, WARN+), with context")
m = LogManager(FakeClock(36_960_000, 7))
alerts = ListAppender(JsonFormatter(), Level.WARN)
m.root.appenders += [ConsoleAppender(), alerts]
pay = m.get("app.pay")
Context.put("req", "r-42")
Context.put("user", "u-1007")
pay.info("charging card ending {}", "4242")
pay.warn('gateway said "retry", attempt {}', 2)
Context.clear()
pay.error("charge failed after {} attempts", 3)
print(" alerts sink:")
for line in alerts.lines:
print(" " + line)
def demo_injection():
print("\n3) A newline in user input cannot forge a second log line")
m = LogManager(FakeClock(37_020_000, 7))
m.root.appenders.append(ConsoleAppender())
name = "bob\n10:17:00.007 INFO [main] app.auth - admin login ok"
m.get("app.auth").warn("failed login for {}", name)
def demo_lazy():
print("\n4) Disabled levels cost a comparison, not a string")
m = LogManager(FakeClock(37_080_000, 7))
sink = ListAppender()
m.root.appenders.append(sink)
log = m.get("app.orders")
order = Expensive()
log.debug("state {}", order)
print(f" debug with placeholder, level INFO: object rendered {Expensive.calls}")
log.debug("state " + str(order))
print(f" debug with string concatenation: object rendered {Expensive.calls}")
log.info("state {}", order)
print(f" info with placeholder: object rendered {Expensive.calls}, lines = {len(sink.lines)}")
def demo_failure():
print("\n5) A sink that throws does not break the caller or the other sinks")
m = LogManager(FakeClock(37_140_000, 7))
good = ListAppender()
m.root.appenders += [BrokenAppender(), good]
m.get("app.jobs").error("nightly export failed: {}", "timeout")
print(f" good sink lines: {len(good.lines)}, failures: {m.failures} ({m.last_failure})")
print(" caller carried on")
def demo_rolling(tmp):
print("\n6) Rolling file: 180 bytes per file, 2 backups, 12 lines of 58 bytes")
m = LogManager(FakeClock(37_200_000, 1000))
path = os.path.join(tmp, "app.log")
roll = RollingFileAppender(path, 180, 2)
m.root.appenders.append(roll)
log = m.get("app.worker")
for i in range(1, 13):
log.info("processed batch {}", f"{i:02d}")
m.shutdown()
for name in ["app.log", "app.log.1", "app.log.2", "app.log.3"]:
p = os.path.join(tmp, name)
if not os.path.exists(p):
print(f" {name:<10} (none)")
continue
with open(p, encoding="utf-8") as f:
lines = f.read().splitlines()
first = lines[0].rsplit(" ", 1)[1]
last = lines[-1].rsplit(" ", 1)[1]
print(f" {name:<10} {os.path.getsize(p):>3} bytes, {len(lines)} lines, batches {first}-{last}")
print(" batches 01-03 were rolled past the last backup and deleted")
def demo_async():
print("\n7) Async appender, queue of 100, worker stuck on a slow write")
m = LogManager(FakeClock(37_260_000, 1))
sink = ListAppender()
gate = GateAppender(sink)
asy = AsyncAppender(gate, capacity=100)
m.root.appenders.append(asy)
log = m.get("app.api")
result = {}
def produce():
Context.put("req", "r-77")
log.info("event {}", 1)
gate.entered.wait() # the worker has taken #1 and is stuck
t0 = time.perf_counter()
for i in range(2, 301):
if i % 25 == 0:
log.error("event {}", i)
else:
log.info("event {}", i)
result["ms"] = (time.perf_counter() - t0) * 1000
t = threading.Thread(target=produce, name="producer")
t.start()
t.join()
print(f" producer logged 300 records (12 of them ERROR) and never waited")
print(f" dropped on arrival: {asy.dropped} INFO, evicted from queue: {asy.evicted} INFO")
gate.release.set()
asy.flush()
asy.close()
seqs = [int(line.split("event ")[1].split(" ")[0]) for line in sink.lines]
errors = sum(1 for line in sink.lines if " ERROR " in line)
print(f" written: {len(sink.lines)}, ERROR written: {errors} of 12, in order: {seqs == sorted(seqs)}")
print(f" last written: {seqs[-5:]}")
print(f" {sink.lines[0]}")
def demo_threads():
print("\n8) 4 threads x 2,500 lines through one logger and one sink")
m = LogManager(FakeClock(37_320_000, 1))
sink = ListAppender()
m.root.appenders.append(sink)
log = m.get("app.load")
def work(n):
for i in range(2500):
log.info("t{} seq {}", n, i)
ts = [threading.Thread(target=work, args=(n,), name=f"w{n}") for n in range(4)]
for t in ts:
t.start()
for t in ts:
t.join()
ok = True
for n in range(4):
mine = [int(line.rsplit(" ", 1)[1]) for line in sink.lines if f" - t{n} seq " in line]
ok = ok and mine == list(range(2500))
print(f" lines: {len(sink.lines)}, every thread's lines complete and in its own order: {ok}")
# ---------------- benchmarks ----------------
class FdAppender(Appender):
"""Writes the text and the newline as two write() calls, optionally without the lock."""
def __init__(self, fd, locked=True):
super().__init__(PlainFormatter(), Level.DEBUG)
self.fd, self.locked = fd, locked
def append(self, r):
line = self.formatter.format(r)
if self.locked:
with self._lock:
os.write(self.fd, line.encode())
os.write(self.fd, b"\n")
else:
os.write(self.fd, line.encode())
os.write(self.fd, b"\n")
class SlowAppender(Appender):
"""Stands in for a sink that does a network round trip per line."""
def __init__(self, delay_s):
super().__init__(PlainFormatter(), Level.DEBUG)
self.delay_s, self.count = delay_s, 0
def write(self, line):
time.sleep(self.delay_s)
self.count += 1
def bench(tmp):
print("bench: disabled DEBUG, 1,000,000 calls, argument has a 100-item toString")
m = LogManager()
log = m.get("bench")
order = BigOrder()
for label, fn in [
("placeholder", lambda: log.debug("state {}", order)),
("f-string", lambda: log.debug(f"state {order}")),
("is_enabled guard", lambda: log.is_enabled(Level.DEBUG) and log.debug(f"state {order}")),
]:
t0 = time.perf_counter()
for _ in range(1_000_000):
fn()
print(f" {label:<17} {time.perf_counter() - t0:6.2f} s")
print("bench: unlocked vs locked, 4 threads x 50,000 lines, text and newline as two writes")
for locked in (False, True):
path = os.path.join(tmp, f"torn-{locked}.log")
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_APPEND)
m = LogManager()
m.root.appenders.append(FdAppender(fd, locked))
log = m.get("bench.torn")
ts = [threading.Thread(target=lambda n=n: [log.info("thread {} line {}", n, i) for i in range(50_000)],
name=f"w{n}") for n in range(4)]
for t in ts:
t.start()
for t in ts:
t.join()
os.close(fd)
with open(path) as f:
lines = f.read().split("\n")[:-1]
bad = sum(1 for line in lines if not (line.count(" - ") == 1 and line.split(" ")[-2] == "line"))
print(f" locked={locked!s:<5} lines={len(lines)} malformed={bad}")
print("bench: 2,000 INFO lines to a sink that takes 0.2 ms per line, caller-side time")
for mode in ("sync", "async"):
m = LogManager()
slow = SlowAppender(0.0002)
sink = AsyncAppender(slow, 8192) if mode == "async" else slow
m.root.appenders.append(sink)
log = m.get("bench.slow")
t0 = time.perf_counter()
for i in range(2000):
log.info("request {} done", i)
caller = time.perf_counter() - t0
if mode == "async":
sink.close()
total = time.perf_counter() - t0
print(f" {mode:<5} caller {caller * 1000:7.1f} ms, all written after {total * 1000:7.1f} ms, written {slow.count}")
def main():
threading.current_thread().name = "main"
with tempfile.TemporaryDirectory() as tmp:
if "--bench" in sys.argv:
bench(tmp)
return
demo_levels()
demo_sinks()
demo_injection()
demo_lazy()
demo_failure()
demo_rolling(tmp)
demo_async()
demo_threads()
if __name__ == "__main__":
main()
Java
// Logging framework: levels, a tree of named loggers, appenders that each have
// their own threshold and formatter, per-thread context, a size-based rolling file,
// and an async appender with a bounded queue that drops INFO before it drops ERROR.
//
// Run: java Logger.java deterministic demos (same output as logger.py)
// java Logger.java --bench timings, which depend on the machine
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.LongSupplier;
public class Logger {
enum Level {
DEBUG(10), INFO(20), WARN(30), ERROR(40), OFF(100);
final int value;
Level(int v) { value = v; }
boolean below(Level other) { return value < other.value; }
}
static String render(String msg, Object... args) {
if (args.length == 0) return msg;
StringBuilder out = new StringBuilder();
int i = 0, a = 0;
while (true) {
int j = msg.indexOf("{}", i);
if (j < 0 || a == args.length) { out.append(msg, i, msg.length()); return out.toString(); }
out.append(msg, i, j).append(args[a++]);
i = j + 2;
}
}
// ---------------- per-thread context (MDC) ----------------
static final class Context {
private static final ThreadLocal<LinkedHashMap<String, String>> MAP =
ThreadLocal.withInitial(LinkedHashMap::new);
static void put(String k, String v) { MAP.get().put(k, v); }
static void clear() { MAP.get().clear(); }
static Map<String, String> snapshot() { return new LinkedHashMap<>(MAP.get()); }
}
/** Everything is captured on the calling thread, at the moment of the call. */
record Rec(long timeMs, Level level, String logger, String thread, String msg, Map<String, String> ctx) {}
// ---------------- formatters ----------------
interface Formatter { String format(Rec r); }
static String clockText(long ms) {
ms %= 86_400_000;
return String.format("%02d:%02d:%02d.%03d", ms / 3_600_000, ms / 60_000 % 60, ms / 1000 % 60, ms % 1000);
}
static String escapeLine(String s) {
return s.replace("\\", "\\\\").replace("\n", "\\n").replace("\r", "\\r");
}
static String jsonStr(String s) {
StringBuilder out = new StringBuilder("\"");
for (char ch : s.toCharArray()) {
switch (ch) {
case '"' -> out.append("\\\"");
case '\\' -> out.append("\\\\");
case '\n' -> out.append("\\n");
case '\r' -> out.append("\\r");
case '\t' -> out.append("\\t");
default -> {
if (ch < 0x20) out.append(String.format("\\u%04x", (int) ch));
else out.append(ch);
}
}
}
return out.append('"').toString();
}
static final class PlainFormatter implements Formatter {
public String format(Rec r) {
StringBuilder line = new StringBuilder(String.format("%s %-5s [%s] %s - %s",
clockText(r.timeMs()), r.level().name(), r.thread(), r.logger(), escapeLine(r.msg())));
if (!r.ctx().isEmpty()) {
StringJoiner j = new StringJoiner(", ", " {", "}");
r.ctx().forEach((k, v) -> j.add(k + "=" + v));
line.append(j);
}
return line.toString();
}
}
static final class JsonFormatter implements Formatter {
public String format(Rec r) {
StringJoiner parts = new StringJoiner(",", "{", "}");
parts.add("\"time\":" + jsonStr(clockText(r.timeMs())));
parts.add("\"level\":" + jsonStr(r.level().name()));
parts.add("\"logger\":" + jsonStr(r.logger()));
parts.add("\"thread\":" + jsonStr(r.thread()));
parts.add("\"msg\":" + jsonStr(r.msg()));
if (!r.ctx().isEmpty()) {
StringJoiner c = new StringJoiner(",", "{", "}");
r.ctx().forEach((k, v) -> c.add(jsonStr(k) + ":" + jsonStr(v)));
parts.add("\"ctx\":" + c);
}
return parts.toString();
}
}
// ---------------- appenders ----------------
/** Filter by threshold, format outside the lock, write one whole line under it. */
static abstract class Appender {
final Formatter formatter;
final Level threshold;
final Object lock = new Object();
Appender(Formatter f, Level threshold) { this.formatter = f == null ? new PlainFormatter() : f; this.threshold = threshold; }
void append(Rec r) throws IOException {
if (r.level().below(threshold)) return;
String line = formatter.format(r);
synchronized (lock) { write(line); }
}
abstract void write(String line) throws IOException;
void close() throws IOException {}
}
static final class ConsoleAppender extends Appender {
ConsoleAppender() { super(null, Level.DEBUG); }
void write(String line) { System.out.println(" " + line); }
}
static final class ListAppender extends Appender {
final List<String> lines = new ArrayList<>();
ListAppender() { this(null, Level.DEBUG); }
ListAppender(Formatter f, Level t) { super(f, t); }
void write(String line) { lines.add(line); }
}
static final class BrokenAppender extends Appender {
BrokenAppender() { super(null, Level.DEBUG); }
void write(String line) throws IOException { throw new IOException("disk full"); }
}
/** app.log is current; app.log.1 the previous file, up to app.log.<backups>. */
static final class RollingFileAppender extends Appender {
final Path path; final long maxBytes; final int backups;
OutputStream out; long size;
RollingFileAppender(Path path, long maxBytes, int backups) throws IOException {
super(null, Level.DEBUG);
this.path = path; this.maxBytes = maxBytes; this.backups = backups;
size = Files.exists(path) ? Files.size(path) : 0;
out = new FileOutputStream(path.toFile(), true);
}
void write(String line) throws IOException {
byte[] data = (line + "\n").getBytes(StandardCharsets.UTF_8);
if (size > 0 && size + data.length > maxBytes) roll();
out.write(data);
out.flush();
size += data.length;
}
private Path numbered(int i) { return Paths.get(path + "." + i); }
private void roll() throws IOException {
out.close();
Files.deleteIfExists(numbered(backups));
for (int i = backups - 1; i >= 1; i--)
if (Files.exists(numbered(i))) Files.move(numbered(i), numbered(i + 1), StandardCopyOption.REPLACE_EXISTING);
Files.move(path, numbered(1), StandardCopyOption.REPLACE_EXISTING);
out = new FileOutputStream(path.toFile(), true);
size = 0;
}
void close() throws IOException { synchronized (lock) { out.close(); } }
}
/**
* Decorator: the caller only enqueues; one worker thread writes to target.
* When the queue is full: a record below WARN is dropped; a WARN or ERROR evicts
* the oldest record below WARN; if the queue holds nothing but WARN/ERROR, the
* caller waits. Errors are never lost, and INFO never makes a request wait.
*/
static final class AsyncAppender extends Appender {
final Appender target; final int capacity;
private final ArrayDeque<Rec> q = new ArrayDeque<>();
private int pending = 0; // queued + being written
private boolean closed = false;
int dropped = 0, evicted = 0;
private final Thread worker;
AsyncAppender(Appender target, int capacity) {
super(null, Level.DEBUG);
this.target = target; this.capacity = capacity;
worker = new Thread(this::run, "log-async");
worker.setDaemon(true);
worker.start();
}
@Override void append(Rec r) throws IOException {
synchronized (lock) {
if (closed) { target.append(r); return; } // late shutdown messages: write directly
while (q.size() >= capacity) {
if (r.level().below(Level.WARN)) { dropped++; return; }
Rec victim = null;
for (Rec x : q) if (x.level().below(Level.WARN)) { victim = x; break; }
if (victim != null) { q.remove(victim); evicted++; pending--; break; }
try { lock.wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; }
}
q.addLast(r);
pending++;
lock.notifyAll();
}
}
void write(String line) { throw new UnsupportedOperationException(); }
private void run() {
while (true) {
Rec r;
synchronized (lock) {
while (q.isEmpty() && !closed) {
try { lock.wait(); } catch (InterruptedException e) { return; }
}
if (q.isEmpty()) return;
r = q.pollFirst();
lock.notifyAll();
}
try { target.append(r); }
catch (Exception e) { System.err.println("log-async: " + e.getMessage()); } // the worker must survive a bad write
synchronized (lock) { pending--; lock.notifyAll(); }
}
}
void flush() throws InterruptedException {
synchronized (lock) { while (pending > 0) lock.wait(); }
}
@Override void close() throws IOException {
synchronized (lock) { closed = true; lock.notifyAll(); }
try { worker.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
target.close();
}
}
// ---------------- loggers ----------------
static final class Log {
final String name; final Log parent; final LogManager manager;
volatile Level level; // null = inherit from parent
final List<Appender> appenders = new java.util.concurrent.CopyOnWriteArrayList<>();
volatile boolean propagate = true;
Log(String name, Log parent, LogManager m) { this.name = name; this.parent = parent; this.manager = m; }
Level effectiveLevel() {
Log lg = this;
while (lg.level == null) lg = lg.parent;
return lg.level;
}
boolean isEnabled(Level l) { return !l.below(effectiveLevel()); }
void log(Level level, String msg, Object... args) {
if (level.below(effectiveLevel())) return; // nothing formatted, nothing allocated
Rec r = new Rec(manager.clock.getAsLong(), level, name, Thread.currentThread().getName(),
render(msg, args), Context.snapshot());
for (Log lg = this; lg != null; lg = lg.parent) {
for (Appender a : lg.appenders) {
try { a.append(r); }
catch (Exception e) { manager.reportFailure(a, e); } // a broken sink must not break the request
}
if (!lg.propagate) break;
}
}
void debug(String m, Object... a) { log(Level.DEBUG, m, a); }
void info(String m, Object... a) { log(Level.INFO, m, a); }
void warn(String m, Object... a) { log(Level.WARN, m, a); }
void error(String m, Object... a) { log(Level.ERROR, m, a); }
}
/** Owns the logger tree. One default instance for the app, fresh ones for tests. */
static final class LogManager {
final LongSupplier clock;
final Log root;
private final Map<String, Log> loggers = new LinkedHashMap<>();
int failures = 0; String lastFailure = "";
LogManager(LongSupplier clock) {
this.clock = clock == null ? System::currentTimeMillis : clock;
root = new Log("root", null, this);
root.level = Level.INFO;
}
synchronized Log get(String name) {
Log lg = loggers.get(name);
if (lg == null) {
int dot = name.lastIndexOf('.');
Log parent = dot < 0 ? root : get(name.substring(0, dot));
lg = new Log(name, parent, this);
loggers.put(name, lg);
}
return lg;
}
synchronized void reportFailure(Appender a, Exception e) {
failures++;
lastFailure = a.getClass().getSimpleName() + ": " + e.getMessage();
}
void shutdown() throws IOException {
Set<Appender> seen = Collections.newSetFromMap(new IdentityHashMap<>());
List<Log> all = new ArrayList<>();
all.add(root);
synchronized (this) { all.addAll(loggers.values()); }
for (Log lg : all) for (Appender a : lg.appenders) if (seen.add(a)) a.close();
}
}
private static final class Holder { static final LogManager DEFAULT = new LogManager(null); }
static Log getLogger(String name) { return Holder.DEFAULT.get(name); }
static LongSupplier fakeClock(long start, long step) {
AtomicLong now = new AtomicLong(start);
return () -> now.getAndAdd(step);
}
// ---------------- demos ----------------
static final class Expensive {
static int calls = 0;
@Override public String toString() { calls++; return "Order(id=9, items=3)"; }
}
/** A toString that does real work: 100 line items, like dumping a request body. */
static final class BigOrder {
final List<String> items = new ArrayList<>();
BigOrder() { for (int i = 0; i < 100; i++) items.add("sku-" + i + ":" + (i % 7 + 1)); }
@Override public String toString() { return "Order[" + String.join(", ", items) + "]"; }
}
/** Blocks inside the first write until released, to freeze the async worker. */
static final class GateAppender extends Appender {
final Appender target;
final CountDownLatch entered = new CountDownLatch(1), release = new CountDownLatch(1);
GateAppender(Appender t) { super(null, Level.DEBUG); target = t; }
@Override void append(Rec r) throws IOException {
entered.countDown();
try { release.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
target.append(r);
}
void write(String line) { throw new UnsupportedOperationException(); }
}
static void demoLevels() {
System.out.println("1) Levels and the logger tree (root INFO, app.db DEBUG)");
LogManager m = new LogManager(fakeClock(36_900_000, 7));
m.root.appenders.add(new ConsoleAppender());
m.get("app.db").level = Level.DEBUG;
Log http = m.get("app.http"), db = m.get("app.db"), pool = m.get("app.db.pool");
http.debug("GET /cart headers={}", 14);
http.info("GET /cart 200 in {} ms", 38);
db.debug("SELECT took {} ms", 4);
pool.debug("borrowed connection {} of {}", 7, 20);
System.out.println(" -- set app.db to WARN at runtime");
db.level = Level.WARN;
pool.debug("borrowed connection {} of {}", 8, 20);
pool.warn("pool exhausted, waited {} ms", 250);
System.out.println(" effective level of app.db.pool: " + pool.effectiveLevel().name()
+ ", of app.http: " + http.effectiveLevel().name());
}
static void demoSinks() {
System.out.println("\n2) Two sinks: console (plain, INFO+) and alerts (JSON, WARN+), with context");
LogManager m = new LogManager(fakeClock(36_960_000, 7));
ListAppender alerts = new ListAppender(new JsonFormatter(), Level.WARN);
m.root.appenders.add(new ConsoleAppender());
m.root.appenders.add(alerts);
Log pay = m.get("app.pay");
Context.put("req", "r-42");
Context.put("user", "u-1007");
pay.info("charging card ending {}", "4242");
pay.warn("gateway said \"retry\", attempt {}", 2);
Context.clear();
pay.error("charge failed after {} attempts", 3);
System.out.println(" alerts sink:");
for (String line : alerts.lines) System.out.println(" " + line);
}
static void demoInjection() {
System.out.println("\n3) A newline in user input cannot forge a second log line");
LogManager m = new LogManager(fakeClock(37_020_000, 7));
m.root.appenders.add(new ConsoleAppender());
String name = "bob\n10:17:00.007 INFO [main] app.auth - admin login ok";
m.get("app.auth").warn("failed login for {}", name);
}
static void demoLazy() {
System.out.println("\n4) Disabled levels cost a comparison, not a string");
LogManager m = new LogManager(fakeClock(37_080_000, 7));
ListAppender sink = new ListAppender();
m.root.appenders.add(sink);
Log log = m.get("app.orders");
Expensive order = new Expensive();
log.debug("state {}", order);
System.out.println(" debug with placeholder, level INFO: object rendered " + Expensive.calls);
log.debug("state " + order);
System.out.println(" debug with string concatenation: object rendered " + Expensive.calls);
log.info("state {}", order);
System.out.println(" info with placeholder: object rendered " + Expensive.calls + ", lines = " + sink.lines.size());
}
static void demoFailure() {
System.out.println("\n5) A sink that throws does not break the caller or the other sinks");
LogManager m = new LogManager(fakeClock(37_140_000, 7));
ListAppender good = new ListAppender();
m.root.appenders.add(new BrokenAppender());
m.root.appenders.add(good);
m.get("app.jobs").error("nightly export failed: {}", "timeout");
System.out.println(" good sink lines: " + good.lines.size() + ", failures: " + m.failures + " (" + m.lastFailure + ")");
System.out.println(" caller carried on");
}
static void demoRolling(Path tmp) throws IOException {
System.out.println("\n6) Rolling file: 180 bytes per file, 2 backups, 12 lines of 58 bytes");
LogManager m = new LogManager(fakeClock(37_200_000, 1000));
Path path = tmp.resolve("app.log");
m.root.appenders.add(new RollingFileAppender(path, 180, 2));
Log log = m.get("app.worker");
for (int i = 1; i <= 12; i++) log.info("processed batch {}", String.format("%02d", i));
m.shutdown();
for (String name : List.of("app.log", "app.log.1", "app.log.2", "app.log.3")) {
Path p = tmp.resolve(name);
if (!Files.exists(p)) { System.out.println(String.format(" %-10s (none)", name)); continue; }
List<String> lines = Files.readAllLines(p);
String first = lines.get(0).substring(lines.get(0).lastIndexOf(' ') + 1);
String last = lines.get(lines.size() - 1).substring(lines.get(lines.size() - 1).lastIndexOf(' ') + 1);
System.out.println(String.format(" %-10s %3d bytes, %d lines, batches %s-%s", name, Files.size(p), lines.size(), first, last));
}
System.out.println(" batches 01-03 were rolled past the last backup and deleted");
}
static void demoAsync() throws Exception {
System.out.println("\n7) Async appender, queue of 100, worker stuck on a slow write");
LogManager m = new LogManager(fakeClock(37_260_000, 1));
ListAppender sink = new ListAppender();
GateAppender gate = new GateAppender(sink);
AsyncAppender asy = new AsyncAppender(gate, 100);
m.root.appenders.add(asy);
Log log = m.get("app.api");
Thread t = new Thread(() -> {
Context.put("req", "r-77");
log.info("event {}", 1);
try { gate.entered.await(); } catch (InterruptedException e) { return; } // the worker has taken #1 and is stuck
for (int i = 2; i <= 300; i++) {
if (i % 25 == 0) log.error("event {}", i); else log.info("event {}", i);
}
}, "producer");
t.start();
t.join();
System.out.println(" producer logged 300 records (12 of them ERROR) and never waited");
System.out.println(" dropped on arrival: " + asy.dropped + " INFO, evicted from queue: " + asy.evicted + " INFO");
gate.release.countDown();
asy.flush();
asy.close();
List<Integer> seqs = new ArrayList<>();
for (String line : sink.lines) seqs.add(Integer.parseInt(line.split("event ")[1].split(" ")[0]));
long errors = sink.lines.stream().filter(l -> l.contains(" ERROR ")).count();
List<Integer> sorted = new ArrayList<>(seqs);
Collections.sort(sorted);
System.out.println(" written: " + sink.lines.size() + ", ERROR written: " + errors + " of 12, in order: "
+ (seqs.equals(sorted) ? "True" : "False"));
System.out.println(" last written: " + seqs.subList(seqs.size() - 5, seqs.size()));
System.out.println(" " + sink.lines.get(0));
}
static void demoThreads() throws InterruptedException {
System.out.println("\n8) 4 threads x 2,500 lines through one logger and one sink");
LogManager m = new LogManager(fakeClock(37_320_000, 1));
ListAppender sink = new ListAppender();
m.root.appenders.add(sink);
Log log = m.get("app.load");
List<Thread> ts = new ArrayList<>();
for (int n = 0; n < 4; n++) {
int id = n;
ts.add(new Thread(() -> { for (int i = 0; i < 2500; i++) log.info("t{} seq {}", id, i); }, "w" + n));
}
for (Thread t : ts) t.start();
for (Thread t : ts) t.join();
boolean ok = true;
for (int n = 0; n < 4; n++) {
List<Integer> mine = new ArrayList<>();
for (String line : sink.lines)
if (line.contains(" - t" + n + " seq ")) mine.add(Integer.parseInt(line.substring(line.lastIndexOf(' ') + 1)));
for (int i = 0; i < 2500; i++) ok &= mine.size() == 2500 && mine.get(i) == i;
}
System.out.println(" lines: " + sink.lines.size() + ", every thread's lines complete and in its own order: " + (ok ? "True" : "False"));
}
// ---------------- benchmarks ----------------
/** Writes the text and the newline as two write() calls, optionally without the lock. */
static final class FdAppender extends Appender {
final FileOutputStream out; final boolean locked;
FdAppender(FileOutputStream out, boolean locked) { super(null, Level.DEBUG); this.out = out; this.locked = locked; }
@Override void append(Rec r) throws IOException {
byte[] text = formatter.format(r).getBytes(StandardCharsets.UTF_8);
if (locked) synchronized (lock) { out.write(text); out.write('\n'); }
else { out.write(text); out.write('\n'); }
}
void write(String line) {}
}
static final class SlowAppender extends Appender {
final long delayNanos; int count = 0;
SlowAppender(long delayNanos) { super(null, Level.DEBUG); this.delayNanos = delayNanos; }
void write(String line) {
long end = System.nanoTime() + delayNanos;
while (System.nanoTime() < end) Thread.onSpinWait();
count++;
}
}
static void bench(Path tmp) throws Exception {
System.out.println("bench: disabled DEBUG, 1,000,000 calls (after warm-up), argument has a 100-item toString");
LogManager m = new LogManager(null);
Log log = m.get("bench");
BigOrder order = new BigOrder();
for (int round = 0; round < 2; round++) {
long t0 = System.nanoTime();
for (int i = 0; i < 1_000_000; i++) log.debug("state {}", order);
long t1 = System.nanoTime();
for (int i = 0; i < 1_000_000; i++) log.debug("state " + order);
long t2 = System.nanoTime();
if (round == 1) {
System.out.printf(" placeholder %6d ms%n", (t1 - t0) / 1_000_000);
System.out.printf(" concatenation %6d ms%n", (t2 - t1) / 1_000_000);
}
}
System.out.println("bench: unlocked vs locked, 4 threads x 50,000 lines, text and newline as two writes");
for (boolean locked : new boolean[]{false, true}) {
Path p = tmp.resolve("torn-" + locked + ".log");
LogManager lm = new LogManager(null);
try (FileOutputStream out = new FileOutputStream(p.toFile(), true)) {
lm.root.appenders.add(new FdAppender(out, locked));
Log tl = lm.get("bench.torn");
List<Thread> ts = new ArrayList<>();
for (int n = 0; n < 4; n++) {
int id = n;
ts.add(new Thread(() -> { for (int i = 0; i < 50_000; i++) tl.info("thread {} line {}", id, i); }, "w" + n));
}
for (Thread t : ts) t.start();
for (Thread t : ts) t.join();
}
List<String> lines = Files.readAllLines(p);
long bad = lines.stream().filter(l -> {
String[] w = l.split(" ");
return !(l.split(" - ", -1).length == 2 && w.length >= 2 && w[w.length - 2].equals("line"));
}).count();
System.out.printf(" locked=%-5s lines=%d malformed=%d%n", locked, lines.size(), bad);
}
System.out.println("bench: 2,000 INFO lines to a sink that takes 0.2 ms per line, caller-side time");
for (String mode : List.of("sync", "async")) {
LogManager lm = new LogManager(null);
SlowAppender slow = new SlowAppender(200_000);
Appender sink = mode.equals("async") ? new AsyncAppender(slow, 8192) : slow;
lm.root.appenders.add(sink);
Log sl = lm.get("bench.slow");
long t0 = System.nanoTime();
for (int i = 0; i < 2000; i++) sl.info("request {} done", i);
long caller = System.nanoTime() - t0;
if (sink instanceof AsyncAppender a) a.close();
long total = System.nanoTime() - t0;
System.out.printf(" %-5s caller %7.1f ms, all written after %7.1f ms, written %d%n",
mode, caller / 1e6, total / 1e6, slow.count);
}
}
public static void main(String[] args) throws Exception {
Path tmp = Files.createTempDirectory("logger");
try {
if (Arrays.asList(args).contains("--bench")) { bench(tmp); return; }
demoLevels();
demoSinks();
demoInjection();
demoLazy();
demoFailure();
demoRolling(tmp);
demoAsync();
demoThreads();
} finally {
try (var s = Files.list(tmp)) { s.forEach(f -> f.toFile().delete()); }
Files.delete(tmp);
}
}
}
What it printed
1) Levels and the logger tree (root INFO, app.db DEBUG)
10:15:00.000 INFO [main] app.http - GET /cart 200 in 38 ms
10:15:00.007 DEBUG [main] app.db - SELECT took 4 ms
10:15:00.014 DEBUG [main] app.db.pool - borrowed connection 7 of 20
-- set app.db to WARN at runtime
10:15:00.021 WARN [main] app.db.pool - pool exhausted, waited 250 ms
effective level of app.db.pool: WARN, of app.http: INFO
2) Two sinks: console (plain, INFO+) and alerts (JSON, WARN+), with context
10:16:00.000 INFO [main] app.pay - charging card ending 4242 {req=r-42, user=u-1007}
10:16:00.007 WARN [main] app.pay - gateway said "retry", attempt 2 {req=r-42, user=u-1007}
10:16:00.014 ERROR [main] app.pay - charge failed after 3 attempts
alerts sink:
{"time":"10:16:00.007","level":"WARN","logger":"app.pay","thread":"main","msg":"gateway said \"retry\", attempt 2","ctx":{"req":"r-42","user":"u-1007"}}
{"time":"10:16:00.014","level":"ERROR","logger":"app.pay","thread":"main","msg":"charge failed after 3 attempts"}
3) A newline in user input cannot forge a second log line
10:17:00.000 WARN [main] app.auth - failed login for bob\n10:17:00.007 INFO [main] app.auth - admin login ok
4) Disabled levels cost a comparison, not a string
debug with placeholder, level INFO: object rendered 0
debug with string concatenation: object rendered 1
info with placeholder: object rendered 2, lines = 1
5) A sink that throws does not break the caller or the other sinks
good sink lines: 1, failures: 1 (BrokenAppender: disk full)
caller carried on
6) Rolling file: 180 bytes per file, 2 backups, 12 lines of 58 bytes
app.log 174 bytes, 3 lines, batches 10-12
app.log.1 174 bytes, 3 lines, batches 07-09
app.log.2 174 bytes, 3 lines, batches 04-06
app.log.3 (none)
batches 01-03 were rolled past the last backup and deleted
7) Async appender, queue of 100, worker stuck on a slow write
producer logged 300 records (12 of them ERROR) and never waited
dropped on arrival: 191 INFO, evicted from queue: 8 INFO
written: 101, ERROR written: 12 of 12, in order: True
last written: [200, 225, 250, 275, 300]
10:21:00.000 INFO [producer] app.api - event 1 {req=r-77}
8) 4 threads x 2,500 lines through one logger and one sink
lines: 10000, every thread's lines complete and in its own order: True
Reading it:
- Demo 1. The first
app.httpDEBUG line is missing, becauseapp.httpinherits INFO from the root.app.dbwas set to DEBUG, so its line and the line fromapp.db.pool(which has no level of its own) are written. Afterapp.dbis switched to WARN at runtime, the pool’s next DEBUG line disappears and its WARN still goes through. Nothing was cached, so nothing had to be invalidated. - Demo 2. One record, two sinks, two formats. The console gets all three lines; the alerts sink only the WARN and the ERROR, as JSON with the quote escaped. The context (
req,user) is on the first two lines and gone from the third, becauseContext.clear()ran in between. In a web server, that clear goes in afinallyat the end of each request; forget it on a thread pool and the next request on that thread inherits the previous user’s id. - Demo 3. The forged line is still there in the output, but on the same line as the real one, after a literal
\n. A log parser that splits on newlines sees one WARN, not a WARN and an INFO. - Demo 4. The placeholder version never rendered the object while DEBUG was off. The concatenated version rendered it and then threw the string away.
- Demo 5.
BrokenAppenderraised “disk full”. The logger caught it, counted it, and the second sink still got the line. The caller did not see an exception. - Demo 6. Each line is 58 bytes, so three fit under 180. Twelve lines make four files’ worth, and with two backups the oldest three batches are gone. Size-based rotation means you choose the disk budget up front:
max_bytes × (backups + 1). - Demo 7. The worker took event 1 and is stuck in the slow write. Events 2 to 101 fill the queue of 100, including the ERRORs at 25, 50, 75 and 100. From 102 onwards every INFO is dropped on arrival (191 of them) and each of the 8 later ERRORs evicts the oldest INFO in the queue. After the gate opens, 101 lines are written, all 12 ERRORs among them, still in order. The producer never waited. The first line says
[producer]andreq=r-77althoughlog-asyncwrote it. - Demo 8. Four threads, 10,000 lines, none lost or torn, and each thread’s own lines in its own order. The order between threads is whatever the scheduler did, which is why the demo checks per-thread order only.
The benchmark numbers
bench-output.txt, one run (8 vCPUs; your numbers will differ, the ratios should not):
| Measurement | Java 21 | Python 3.13 |
|---|---|---|
1M disabled DEBUG calls, placeholder "state {}", order | 9 ms | 0.20 s |
| 1M disabled DEBUG calls, string built first | 723 ms | 1.05 s |
1M disabled DEBUG calls, is_enabled guard then f-string | n/a | 0.08 s |
| 200k lines, 4 threads, text and newline as two writes, no lock: malformed lines | 108,984 | 3,361 |
| Same, with the appender lock | 0 | 0 |
| 2,000 lines to a 0.2 ms/line sink, synchronous: time the caller spent | 404.9 ms | 529.5 ms |
Same through AsyncAppender: time the caller spent | 0.9 ms | 7.1 ms |
| Same, time until the last line was written | 405.5 ms | 535.3 ms |
The last two rows are the honest summary of async logging. It does not make logging faster. The sink still takes 0.2 ms a line and the last line lands at the same time either way. It moves the wait off the request thread. If the sink is slower than the rate you produce lines at, async only delays the moment you hit the full-queue policy, which is why the policy is the real design.
(The Java slow sink spins for 0.2 ms; the Python one sleeps, and time.sleep(0.0002) takes a little longer than asked, hence 529 ms against 405 ms.)
Where interviewers take it next
“Change log levels without a restart.” Logger.level is already read on every call, so this is a config watcher, or an admin endpoint, that calls manager.get(name).level = .... Make the field volatile in Java (it is in the code) so other threads see the change. The bug to avoid is the one from the tree section: caching effective levels without pushing changes down.
“A rate-limited logger: at most 100 lines a second from one call site.” Put a token bucket in front of the appenders, keyed by logger name or by message template, and log one summary line, “suppressed 4,212 messages from app.db in the last 10 s”, when the bucket refills. The rate limiter lesson builds the bucket.
“Send logs to a central service.” Another appender, but it must batch (one HTTP request per 500 lines, not per line), retry with backoff, and cap its own buffer. In production most teams write to a local file or stdout and let an agent (Fluent Bit, Vector, the Kubernetes node agent) ship it, so the application never blocks on the network at all. That is the answer I would give.
“Log exceptions.” Add a throwable field to the record. SLF4J treats a trailing Throwable argument as the exception, not a placeholder value. The formatter prints the stack trace; the JSON formatter puts it in one escaped field so a multi-line stack trace stays one record.
“Make the request id follow work onto a thread pool.” A thread-local does not cross threads. Wrap submitted tasks so they copy the submitting thread’s context in and clear it after. In Python, contextvars copy into asyncio tasks automatically, which a threading.local does not.
“Two processes write the same file.” Separate files per process, or write to stdout and let the platform collect it. Rotation by renaming breaks when another process still has the old file open. This is why I put it out of scope.
“What if the disk is full?” Demo 5: the appender throws, the logger counts it and carries on. Add rate-limited reporting of the failure to stderr, and a health check on the failure counter, so someone notices.
The next case study, a rate limiter, is the other half of “a rate-limited logger”: four algorithms behind one interface, and the question of what “5 per second” actually means.
Mistakes worth avoiding
- String building before the level check.
log.debug("user " + user)costs the fulltoStringon every call even when DEBUG is off. On a hot path with a big object, it shows up in profiles. - Formatting on the worker thread. The record shows state from a few milliseconds later, and the wrong thread name.
- An unbounded async queue. A slow sink turns into an
OutOfMemoryErroran hour later, far from the cause. - Blocking on every log call when the queue is full, without saying so. It is a legitimate choice for an audit log, and the wrong default for request logging.
- No
close()on shutdown. The last lines before a crash are the ones you need, and they are the ones still in the queue. - Letting a sink’s exception reach the caller. Logging must never be the reason a request failed.
- Unescaped newlines in plain text logs. It lets anyone who can type into a form write fake log lines.
- A private-constructor singleton. Tests cannot get a clean logger tree, and configuration leaks from one test to the next.
- Chain of responsibility per level. It answers “which handler” when the question is “which sinks”.
Key takeaways
- Two thresholds: the logger decides if anyone cares, the appender decides if this sink wants it.
- Loggers form a tree by dotted name; levels are inherited at call time, so a runtime change applies to the whole subtree.
- Check the level first, then render the message, the thread name and the context on the calling thread.
- Appenders are observers, formatters are strategies, async is a decorator. The textbook level chain is the wrong pattern.
- An async appender is a bounded queue plus a full-queue policy. Drop low levels first, never drop errors, and count what you drop.
- One lock per appender, held only for the write. Without it, more than half of the lines from four Java threads came out torn.
Exercises
- Add a TRACE level below DEBUG. Which classes change? (If the answer is more than
Level, look again at where levels are compared.) - Change
AsyncAppenderto the “block the caller” policy, rerun demo 7 with a timer thread that opens the gate after 50 ms, and measure how long the producer waited. - Add a
SamplingAppenderdecorator that passes through every WARN and ERROR but only 1 in N INFO lines. Where does it sit relative toAsyncAppender, and does the order matter? - Add time-based rotation (a new file at midnight) to
RollingFileAppenderwithout changingwrite’s callers. Use the injected clock so you can test midnight without waiting for it.
Quiz
app.dbis set to DEBUG and the console appender’s threshold is INFO. Does a DEBUG line fromapp.db.poolreach the console?- Why is the message rendered on the calling thread and not on the async worker?
- The async queue of 100 is full of INFO records and an ERROR arrives. What happens to the ERROR, to the caller, and to the queue?
- Why does
effective_level()walk the parent chain on each call instead of being computed once when the logger is created? - What is wrong with
DebugLogger → InfoLogger → ErrorLoggeras the core of a logging framework?
Show answers
- No. The logger lets it through (its effective level is DEBUG, inherited from
app.db), and the console appender drops it at its own INFO threshold. Another appender with a DEBUG threshold would get it. - By the time the worker runs, mutable arguments may have changed and the current thread is
log-async, so the line would show later state and the wrong thread. The context (request id) is thread-local and does not exist on the worker either. - The ERROR evicts the oldest INFO in the queue (the evicted counter goes up), joins the back of the queue, and the caller returns without waiting. It would wait only if the queue held nothing but WARN and ERROR.
- So a level change at runtime applies to every child at once. A copy taken at creation goes stale the moment someone changes a parent’s level, unless every change is pushed down to all descendants.
- It ties levels to classes, so adding a level means new classes and relinking, and it routes each message to one handler while a real record has to go to several sinks with different thresholds and formats. Fan-out to appenders (Observer) with a level check in each is the right shape.