Design a Logging Framework
You'll learn to
- -Break a logging framework into levels, appenders and formatters, and name the pattern behind each
- -Run a chain where each destination filters by its own minimum level
- -Add a new destination by writing one new class, and explain why a Singleton is defensible here
A logging framework is a favorite LLD prompt because a good design naturally combines three patterns you already know, without any new ones. That makes it a good test of whether you can compose patterns, not just name them one at a time. A log is the running diary a program writes about itself: what it did, and what went wrong.
Step 1: Log Levels and the Filtering Chain
The four levels run from least to most serious: DEBUG, INFO, WARNING, ERROR. A logger set to WARNING should suppress DEBUG and INFO but let WARNING and ERROR through. That maps onto Chain of Responsibility. Each handler in a chain decides whether a message is serious enough for it, and then passes the message along either way.
from enum import IntEnum
class LogLevel(IntEnum):
DEBUG = 1
INFO = 2
WARNING = 3
ERROR = 4
class LogMessage:
def __init__(self, level: LogLevel, text: str):
self.level = level
self.text = text
class LogHandler(ABC):
def __init__(self, min_level: LogLevel):
self._min_level = min_level
self._next: "LogHandler | None" = None
def set_next(self, handler: "LogHandler") -> "LogHandler":
self._next = handler
return handler
def handle(self, message: LogMessage) -> None:
if message.level >= self._min_level:
self._write(message)
if self._next:
self._next.handle(message)
@abstractmethod
def _write(self, message: LogMessage) -> None: ...Step 2: Appenders as Independent Handlers
An appender is a destination a log line is written to, such as the console, a file or a remote service. Each has its own minimum level and its own formatter. A console appender might show everything from DEBUG up, while a file keeps only WARNING and above. Both sit in the same chain, and both see every message.
class ConsoleAppender(LogHandler):
def __init__(self, min_level: LogLevel, formatter: "LogFormatter"):
super().__init__(min_level)
self._formatter = formatter
def _write(self, message: LogMessage) -> None:
print(self._formatter.render(message))
class FileAppender(LogHandler):
def __init__(self, min_level: LogLevel, formatter: "LogFormatter", filename: str):
super().__init__(min_level)
self._formatter = formatter
self._filename = filename
def _write(self, message: LogMessage) -> None:
with open(self._filename, "a") as f:
f.write(self._formatter.render(message) + "\n")Step 3: Formatters as a Swappable Strategy
How a message looks (plain text, JSON, a particular timestamp style) is independent of where it goes. That is a clean Strategy split. A plain formatter and a JSON formatter both offer render(message) -> str, and either appender can use either one without changing.
Step 4: A Singleton Logger Registry
The entry point is a single global Logger, so any code can write Logger().log(...) without being handed a logger. This is the defensible Singleton from the Singleton chapter. Logging is called from deep inside almost everything, and threading a logger through every function would cost real effort for little benefit.
class Logger:
_instance: "Logger | None" = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance._chain = None
return cls._instance
def configure(self, chain_head: LogHandler) -> None:
self._chain = chain_head
def log(self, level: LogLevel, text: str) -> None:
if self._chain:
self._chain.handle(LogMessage(level, text))
# Application code anywhere just does:
Logger().log(LogLevel.ERROR, "Payment failed")Run It
The demo wires the whole design together: a console appender at DEBUG with a plain formatter, a file-like appender at WARNING with a JSON formatter, and a webhook appender at ERROR. Three messages go in. Check which destination received which, and note the last class, which stands in for the interviewer's follow-up about sending errors to chat.
The console shows all three messages, the file keeps only the error, and the webhook fires once, for the error. Adding that webhook destination touched no existing class.
Present the design by naming the patterns: "Chain of Responsibility for level filtering, Strategy for formatting, Singleton for the global entry point." Naming all three is exactly the composition skill this problem tests.
Interview Signal is part of Pro
See a real weak answer next to a real strong one for this exact topic.
Quiz is part of Pro
Test what you just read with a short quiz, and bank the XP.
Forge Level 37: Logging Framework asks you to implement a Singleton Logger that filters by minimum severity level, graded by running your actual code against real test cases.
Discussion0
Join the Discussion
Sign in to leave comments, reply to others, or like insights.
No comments yet. Be the first to start the thread!