Logger
easy · levels, filtering, sink injection
Brief-reported interview attribution (unverified): Amazon, Microsoft
How to approach an LLD roundRequirements
- Functional: log at DEBUG/INFO/WARN/ERROR, drop messages below the configured level, format as
[LEVEL] message, deliver to a sink or keep in memory. - Non-functional: the delivery target must be swappable without touching the logger; an unknown level is a hard error (ValueError).
- Out of scope: log rotation, async writing, structured/JSON logs.
Statement
Design a logging framework. Levels are DEBUG < INFO < WARN < ERROR.
The logger is created with a level; messages below that level are dropped.
log(level, message) formats a message as "[LEVEL] message". Output goes to a
sink callable passed to the constructor, or to an internal list (read via
messages()) when no sink is given. Invalid levels raise ValueError.
class Logger:
def __init__(self, level="INFO", sink=None):
# sink: callable taking one formatted string, or None
def set_level(self, level):
# raises ValueError for an unknown level
def log(self, level, message):
# raises ValueError for an unknown level; drops messages below the set level
def debug(self, message):
def info(self, message):
def warn(self, message):
def error(self, message):
def messages(self):
# -> list of formatted strings (empty when a sink is used)Rules. The default level is "INFO". set_level and log with an unknown
level raise ValueError. A dropped message is never sent to the sink and never
stored.
Tests use explicit inputs and injected clocks/callbacks. No network, real threads or application-server execution is involved.
Class design (SOLID)
LogRecord (level + formatted text; SRP). Handler (ABC interface; where records go — DIP) with ListHandler and CallableHandler (OCP — a file or network handler is a new subclass). Logger checks the level and formats, and depends on the Handler, not on a list (DIP). Pattern: Strategy (handler).
The optional constructor handler accepts any object implementing emit(record). Existing callable sink behavior is unchanged; supply either a handler or a sink, not both.
Public demo
# Public demo: run after implementing the class API above.
l = Logger()
l.debug('dropped')
l.info('started')
l.warn('slow')
l.error('failed')
print(l.messages())Reference solution and hidden tests
Locked. Open the interactive editor and attempt the problem; the reference, hidden test descriptions, pattern explanation and complexity are available only after an explicit reveal.
Concurrency
Loggers are shared by every thread. The level check and the emit must not interleave with a set_level call in a way that loses a message: guard log/set_level with one lock per logger (or make the level atomic). The reference is single-threaded; the lock is described here.
Trade-offs & extensions
Formatting is a plain string — cheap and readable. Extending: a Formatter interface for JSON output and an async Handler that batches writes.
Starter code
from abc import ABC, abstractmethod
class LogRecord:
def __init__(self, level, message):
"""sink: callable taking one formatted string, or None"""
pass
def formatted(self):
"""Implement the return value and rules in the API contract."""
pass
class Handler(ABC):
@abstractmethod
def emit(self, record):
"""Implement the return value and rules in the API contract."""
pass
class ListHandler(Handler):
def __init__(self):
"""sink: callable taking one formatted string, or None"""
pass
def emit(self, record):
"""Implement the return value and rules in the API contract."""
pass
class CallableHandler(Handler):
def __init__(self, sink):
"""sink: callable taking one formatted string, or None"""
pass
def emit(self, record):
"""Implement the return value and rules in the API contract."""
pass
class Logger:
def __init__(self, level='INFO', sink=None, handler=None):
"""sink: callable taking one formatted string, or None"""
pass
def set_level(self, level):
"""raises ValueError for an unknown level"""
pass
def log(self, level, message):
"""raises ValueError for an unknown level; drops messages below the set level"""
pass
def debug(self, message):
"""Implement the return value and rules in the API contract."""
pass
def info(self, message):
"""Implement the return value and rules in the API contract."""
pass
def warn(self, message):
"""Implement the return value and rules in the API contract."""
pass
def error(self, message):
"""Implement the return value and rules in the API contract."""
pass
def messages(self):
"""-> list of formatted strings (empty when a sink is used)"""
pass
Each test has a five-second execution limit. Your practice drafts and solved progress stay in this browser.
Return to the Python interpreter