AlgoViz

Design a logging library

medium 75 min

Levels, 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

0:00 / 4:58

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

  1. 1980s

    Eric Allman writes syslog as a part of Sendmail. Levels and many receivers are already there.

  2. January 2001

    The Apache project releases Log4j. Named loggers in a tree, appenders and layouts become the model for most languages.

  3. February 2002

    PEP 282 proposes a logging system for Python's standard library, with loggers, handlers and formatters.

  4. March 2009

    RFC 5424 describes the syslog protocol anew, with fields beside the message.

  5. August 2015

    The Log4j 1 line reaches its end of life. Log4j 2 and others take its place.

  6. December 2021

    CVE-2021-44228: Log4j 2 looked up names inside logged text. Logged text must be data only.

  7. 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.

  1. 1ApproachWhat this question tests, where it gets hard, and how to spend the time.
  2. 2ScopeAsk what changes the design, then commit to a short list.
  3. 3API and dataThe contract first, then the data that serves it.
  4. 4DesignStart with the smallest system that works. Change it only when something breaks.
  5. 5Deep divesCompare the options before you open them, then say which you would pick.
  6. 6Explain your choicesAnswer first. Then compare your reasoning.
  7. 7By levelThe same question is judged differently for mid, senior and staff.
  8. 8MockAnswer against the clock, then score yourself.

How it works

Step through the idea, or press Play.

Step 1 of 4

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.

The talking tubes of the good ship Pelican
INFO upallallERROR

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

AskIf yesIf no
Several places at once?Sinks in a list, each with its own levelStill an interface: tests need a second one
Different looks?A formatter for each sinkOne formatter, same interface
Levels for parts of the program?A tree of named loggersOne logger, one level
Many threads?A lock for each sink, records that do not changeSay that you assume one thread
May a line be lost?A bounded queue with a counterThe caller waits for the disk: say what that costs
Change levels while running?Read the level at each callFix it at start

Levels

Four levels, and one that is not for writing

LevelNumberMeansWho reads it
DEBUG10Details for one problemA developer, for an hour
INFO20Normal events worth knowingAnybody looking back
WARN30Odd, but it went onThe team, this week
ERROR40Something did not workSomeone, now
OFF100Write nothing. Only a threshold, never the level of a recordNobody
Gaps of ten leave room for a level in between. The numbers are ours; the order is what counts.

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

Logger+ instance: Logger+ log(level, text)

1/4One global logger

A static instance that everybody reaches for. Tests cannot replace it.

extends (is a)

Place, look and speed are three separate questions. A tree of classes can answer only one of them.
Python
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 request
Six problems in twelve lines: text built before the check, levels as strings, one if 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

Logger- parent: Logger?- level: Level?- sinks: List<Sink>+ log(level, text, fields)+ enabled(level): bool+ addSink(sink)

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)

The white diamond at a sink: several loggers may share one, and it lives on without them.

What each class knows, and does not know

ClassKnowsDoes not know
LoggerIts name, its parent, its sinksFiles, formats, locks of sinks
RecordWhat happenedWho will read it
SinkOne place, one lockWhich logger sent the record
FormatterHow a line looksWhere the line goes
LogManagerAll loggers, so that it can close their sinksAny 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

Failing is not a field in the small version. The next record simply tries again.

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