Design a logging library
medium 75 minLevels, a tree of loggers, sinks and formatters, then the hard part: full disks, slow networks, lost lines and many threads.
Video lesson · Chapter 1 of 6
Make a prediction
Theory
Read or listen first. About 2 min.
What it is
A logging library takes short reports from all parts of a program and brings the wanted ones to the right places in the right form. The program says what happened. The library decides whether, where and how it is written.
Its core is small: a logger compares levels, a record holds the facts, sinks are places, formatters are looks. Loggers have names with dots and form a tree, so that a level can be set for a whole branch.
It is a favourite interview problem because the happy path takes ten minutes and the rest can fill a day: threads, queues, crashes, rotation, secrets.
Why it exists
print cannot be switched off, has no place but one, and knows no importance. As soon as two people want different things from the same program, the decision must leave the line that reports.
The library lives inside every request. So its design goal is unusual: it must do little, rarely wait, and never fail visibly. A logger that breaks a payment is worse than none.
The same shape returns everywhere: events, filters, several receivers, slow receivers. Who can build a logger can build a notifier, an audit stream or a metrics client.
A short history
1980s
Eric Allman writes syslog as a part of Sendmail. Levels and many receivers are already there.
January 2001
The Apache project releases Log4j. Named loggers in a tree, appenders and layouts become the model for most languages.
February 2002
PEP 282 proposes a logging system for Python's standard library, with loggers, handlers and formatters.
March 2009
RFC 5424 describes the syslog protocol anew, with fields beside the message.
August 2015
The Log4j 1 line reaches its end of life. Log4j 2 and others take its place.
December 2021
CVE-2021-44228: Log4j 2 looked up names inside logged text. Logged text must be data only.
August 2023
Go 1.21 brings structured logging,
log/slog, into the standard library.
Words to know
- Level
- How important a record is, and the threshold from which it is wanted.
- Effective level
- The first level found on the way from a logger to root.
- Record
- The facts of one event, made once and never changed.
- Sink
- A place for lines. Others say handler or appender.
- Formatter
- Turns a record into a line. Others say layout or encoder.
- Propagation
- A record goes on to the sinks of the parents. Logback calls it additivity.
- Structured logging
- Values travel as fields and not inside a sentence.
- Rotation
- Closing a file at a size or time and beginning a new one.
- Backpressure
- A slow receiver makes the sender wait, or forces it to drop.
- Log injection
- Input with line breaks that looks like lines of its own.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
Solve it like an interview
New to it? Start with Approach. Revising? Go straight to the mock.
- 1ApproachWhat this question tests, where it gets hard, and how to spend the time.
- 2ScopeAsk what changes the design, then commit to a short list.
- 3API and dataThe contract first, then the data that serves it.
- 4DesignStart with the smallest system that works. Change it only when something breaks.
- 5Deep divesCompare the options before you open them, then say which you would pick.
- 6Explain your choicesAnswer first. Then compare your reasoning.
- 7By levelThe same question is judged differently for mid, senior and staff.
- 8MockAnswer against the clock, then score yourself.
How it works
Step through the idea, or press Play.
Wanted?. The logger compares levels before anything is built.
Understand it
Start here
What a logger does when nobody looks
Every program writes lines about itself, and somebody reads them on a bad day. The library in between seems simple: take a text, write it. Then it must also be quiet when asked, write to several places, survive a full disk, serve many threads, and never slow down the program it watches. Let us begin on a ship.
Four jobs, and who has each
Is it wanted?
Logger. Compares levels before any work is done. Most calls in a running program end here.
What happened?
Record. Time, level, name, message, fields. It cannot change, so it can be shared.
Where does it go?
Sink. A file, a stream, memory, a network. Its own level and its own lock.
How does it look?
Formatter. Text for people, JSON for machines. It also makes sure one record is one line.
The life of one call
Questions
Six questions, and what each answer changes
| Ask | If yes | If no |
|---|---|---|
| Several places at once? | Sinks in a list, each with its own level | Still an interface: tests need a second one |
| Different looks? | A formatter for each sink | One formatter, same interface |
| Levels for parts of the program? | A tree of named loggers | One logger, one level |
| Many threads? | A lock for each sink, records that do not change | Say that you assume one thread |
| May a line be lost? | A bounded queue with a counter | The caller waits for the disk: say what that costs |
| Change levels while running? | Read the level at each call | Fix it at start |
Levels
Four levels, and one that is not for writing
| Level | Number | Means | Who reads it |
|---|---|---|---|
| DEBUG | 10 | Details for one problem | A developer, for an hour |
| INFO | 20 | Normal events worth knowing | Anybody looking back |
| WARN | 30 | Odd, but it went on | The team, this week |
| ERROR | 40 | Something did not work | Someone, now |
| OFF | 100 | Write nothing. Only a threshold, never the level of a record | Nobody |
A level is a threshold: the logger set to INFO takes INFO and everything above. OFF is above everything, so nothing passes. If somebody writes a record at OFF, an easy comparison would let it through everywhere. That is why enabled also asks for level < OFF.
Which level applies to ship.engine.pump?
First try
The design most people draw first
A Singleton with if for each place, or a subclass for each mixture. Both answer three questions in one class.
The design to avoid: a class for every mixture
1/4One global logger
A static instance that everybody reaches for. Tests cannot replace it.
extends (is a)
class Logger: _instance = None def log(self, level, message): text = f"{datetime.now()} {level} {message}" # built for every call if level == "DEBUG" and not self.debug: # strings, and one if for each level return if self.to_console: print(text) if self.to_file: open("app.log", "a").write(text + "\n") # opened each time, never closed if self.to_mail and level == "ERROR": smtplib.SMTP("mail").sendmail(...) # seconds, inside the caller's requestif for each place, a file that is never closed, mail inside the caller's request, and no lock.Better
The design to reach
The design to reach: logger, sink, formatter
1/6The logger decides: is it wanted?
A logger has a name, perhaps a level, and a parent it asks when it has none.
owns (dies together)depends onhas (lives on)usesimplementsextends (is a)
What each class knows, and does not know
| Class | Knows | Does not know |
|---|---|---|
| Logger | Its name, its parent, its sinks | Files, formats, locks of sinks |
| Record | What happened | Who will read it |
| Sink | One place, one lock | Which logger sent the record |
| Formatter | How a line looks | Where the line goes |
| LogManager | All loggers, so that it can close their sinks | Any record |
Where does the choice of place and look belong?
BreaksA subclass of Logger for each mixture
- How
- JsonFileLogger, AsyncJsonFileLogger and so on.
- Limit
- The number of classes is a product, and one record cannot go to two places.
- Choose when
- Never, beyond one place and one look.
WorksA chain of handlers by level
- How
- Each handler writes if its level fits and passes the record on. This is chain of responsibility.
- Limit
- A chain is for one that answers. Here all of them may. Order starts to matter although it should not.
- Choose when
- If they ask for that pattern by name. Say what a plain list does better.
StrongA list of sinks, each with a formatter
- How
- The logger walks over its sinks. Each decides by its own level.
- Limit
- One more object to set up.
- Choose when
- Nearly always. Five small classes cover six mixtures.
Life
The life of a sink
Open, closed, and what is allowed when
Threads
Two threads, one line
Format outside, write inside
A lock for each sink
- The console does not wait for the network
- Formatting is outside, so it can run side by side
- The order inside one file is the order of the locks
A lock for the whole library
- One slow sink stops every thread at every log call
- A sink that logs waits for itself
- Nobody can say what the lock protects
Tree
Why names have dots
ship.engine.pump is a place in a tree. Two things follow from it. Levels come down: set DEBUG on ship.engine and everything below becomes talkative. Records go up: a sink on root receives what all the others say. Neither needs a list of loggers to keep up to date.
Levels come down, records go up
Summary
The whole topic in one minute.
One call goes through three questions. The logger asks if it is wanted, without building anything. The sinks on the way to root ask if it is wanted there. The formatter makes one line of it. Place and look can be combined freely because they are two objects.
The hard half is failure. Sinks break, so each call has its own try. Disks are slow, so slow sinks get a bounded queue that drops small levels first and counts them. Programs end, so close refuses, wakes, waits with a limit and closes. For each of these, say which lines are lost.
- Logger: wanted or not. Sink: where. Formatter: how it looks. Record: the facts, unchangeable.
- Check the level before anything is built. The refused call is the common one.
- No level means: ask the parent. Root always has one.
- The level is asked where the call is made. On the way up only the sinks filter.
- Format outside the lock, write a whole line inside it, one lock for each sink.
- A sink's error is caught and reported aside. A logger must not break the program.
- A queue needs a size, a rule for full, a counter, and a close that waits.
- One record, one line: line breaks are escaped by the formatter.
Sources
- Python documentation: logging
- Python documentation: logging.handlers
- PEP 282: A Logging System
- Logback manual: architecture
- Logback manual: MDC
- Log4j 2: asynchronous loggers
- Apache Logging Services: security
- Apache Log4j 1: end of life
- zap: FAQ on sampling
- spdlog
- The Go blog: structured logging with slog
- Go: package log/slog
- systemd: journald.conf
- Docker: configure logging drivers
- Linux manual: logrotate
- Linux manual: write
- Linux manual: fsync
- RFC 5424: The Syslog Protocol
- OWASP: logging cheat sheet
- CWE-117: improper output neutralization for logs
- Wikipedia: Syslog
- Wikipedia: Log4j