Case study: logging framework
What you will learn on this page
Section titled “What you will learn on this page”- How to split a logging library into a few small parts, each with one job: a logger that decides whether to log, a log system that sends a record to the right places, sinks that write it, and formatters that turn it into text.
- Why the log system is an object that
mainmakes and passes on, not a global singleton, and what that buys in tests and at shutdown. - How a single unescaped newline lets a user write a fake line into your log, and the small function that stops it.
- How an asynchronous sink keeps a slow disk away from the threads that log: a bounded queue, a worker thread, and a rule for what happens when the queue is full.
- How
flushand shutdown can promise “everything accepted is written”, and how to test that promise without sleeping and hoping. - How a change (fields that a program can search, JSON lines, and a file that rotates) lands in a few files, and how the compiler finds some of the places for you.
This page follows the order in How to approach a case study. It assumes Decorator, Chain of Responsibility, and Backpressure. The Observability page covers what to log; this page builds the thing that logs it.
The request
Section titled “The request”“We need a logging library for our services.”
A logging library can mean a call that prints a line, a client for a log-collection service, or a full framework with configuration files and plug-ins. The first job is to find out what the team actually needs, and what must never go wrong.
Clarifying questions
Section titled “Clarifying questions”Each question is here because its answer changes the design.
| Question | Answer (from the team) | What it changes |
|---|---|---|
| Who calls it? | Our own services: a payments service, an HTTP front end, background jobs. All C++, all in one process each. | An in-process library. No network protocol, no other languages. |
| Where should the lines go? | Warnings and errors to the console, for whoever is watching. Everything to a file, for later. | Several destinations, each with its own lowest level. |
| What must a line show? | The time to the millisecond, in UTC; the level; which part of the program; the message. Short lines on the console. | Two formats. Times in UTC with milliseconds. |
| Can we turn on debug output for one part while it runs? | Yes. When the HTTP code misbehaves we want its debug lines, but not everyone’s. | A level per named logger, changeable at run time. |
| Where is the file? | On a network disk. Writes are usually fast, sometimes take a second. | Writing to the file must not happen on the thread that logs: an asynchronous sink. |
| If the disk stalls for a minute, what then? | Memory must not grow without limit. Losing some info lines is acceptable if we know how many. Errors must not be lost. | A bounded queue. Below error: drop and count. Error: wait for room. |
| If logging fails (disk full), may a payment fail? | Never. Logging must not break the thing it reports on. | Logging never throws into the caller. Failures are counted instead. |
| What happens at shutdown? | Lines that were logged must reach the file. The last lines before a shutdown are often the important ones. | Flush and shutdown write everything already accepted. |
| Do your tests run several services in one test program? | Yes, and each test wants to check what was logged. | No global logger. Each test makes its own log system with a sink that keeps records in memory. |
| Configuration files? Log levels from the environment? | Not now. The program sets things up in main. |
No configuration parser. The routes are fixed when the system is made. |
| How much do you log? | A few thousand lines a second at peak, more with debug on. Most calls are debug lines that are switched off. | A disabled call must be cheap, and must not build its message. |
Two answers shape most of the design. “A payment must never fail because of logging” turns every write into something that may fail quietly but must be counted. “Each test wants to check what was logged” rules out the usual shortcut, one global logger, before any code exists.
Confirmed:
- Named loggers, four levels, a level per logger that can change while the program runs.
- Destinations (sinks) with a lowest level each: console, file, and a memory sink for tests.
- Two text formats, with time in UTC to the millisecond.
- An asynchronous sink with a bounded queue, a drop-or-wait rule, and counts.
- Flush and shutdown that write everything accepted.
- Logging never throws into the caller.
Assumed (to confirm with the team; see Assumptions):
- The text is UTF-8 or plain ASCII. The library does not check it.
- Every sink is set up in
main; none is added later. - One process writes each file.
Out of scope: configuration files, sending logs over the network,
hierarchical logger names (a level for http that also applies to
http.client), log levels from environment variables, and file
rotation (which arrives as a change, below).
Requirements
Section titled “Requirements”Functional requirements.
- FR-1 Named loggers. A component asks the log system for a logger
by name, such as
"payments". The same name always gives the same logger. - FR-2 Levels. Four levels,
debug<info<warn<error. A logger passes on records at or above its level. Each logger’s level can be changed while the program runs. - FR-3 Sinks. The system sends each record to every sink whose lowest level it reaches. Console and file sinks write lines; a memory sink keeps records for tests.
- FR-4 Formats. A full line (time, padded level, logger, message) for files and a short line (level, logger, message) for the console. A message can never produce a line of its own.
- FR-5 Asynchronous writing. A sink can be wrapped so that records are written on a thread of its own. Its queue is bounded. When it is full, a record below a chosen level is dropped and counted; a record at or above it waits for room.
- FR-6 Flush and shutdown.
flushreturns once everything accepted before it is written. Destroying the system writes everything accepted. - FR-7 Failures. A logging call never throws. A failing sink does not stop the other sinks, and each failure is counted.
Non-functional requirements.
- NFR-1 Thread safety. Any thread may log at any time. Lines never interleave, and records from one thread reach a sink in the order that thread logged them.
- NFR-2 Cheap when switched off. A call below the logger’s level costs one atomic load and returns. A message passed as a function is not built at all.
- NFR-3 Bounded memory. An asynchronous sink’s queue holds at most its capacity of records. Beyond the queue there is only the record the worker is writing and one copy for each caller waiting for room.
- NFR-4 Testable. No global state. The clock is passed in, so a test can check exact lines. Every thread that logs calls it, so it must be safe to call from several threads at once.
- NFR-5 Safe output. Text from users (names, URLs, errors from other systems), which arrives in messages and later in field values, cannot forge a line. Logger names come from the program’s own code and are written as they are. See Security boundaries.
NFR-2 is a design target, not a measurement: the code does one relaxed atomic load and returns, and this page has no timings.
Use cases and acceptance criteria
Section titled “Use cases and acceptance criteria”The tests are named after these criteria. See Use cases, user stories, and acceptance criteria.
UC-1 A component logs a record.
- AC-1.1 A logger passes on records at or above its level, and drops those below it.
- AC-1.2 Asking for the same name twice gives the same logger; a different name gives a different one.
- AC-1.3 Changing one logger’s level takes effect at once and changes no other logger.
- AC-2.1 Each sink gets exactly the records at or above its own lowest level.
- AC-2.2 A record carries the logger’s name, the level, the message, and the time from the system’s clock.
- AC-3.1 The two formats are exact, to the character.
- AC-3.2 A message with a newline in it still makes one line.
- AC-4.1 A message passed as a function is not built when the level is off.
- AC-5.1 A file sink appends whole lines, also after the program opens it again. A file that cannot be opened is an exception when the sink is made.
UC-2 A slow destination.
- AC-6.1 An asynchronous sink writes every record, in order, on a thread that is not the caller’s.
- AC-6.2 With the queue full, a record below
erroris dropped and counted, and the caller does not wait. - AC-6.3 With the queue full, an
errorwaits for room and is written; the queue never holds more than its capacity.
UC-3 Flush and shutdown.
- AC-7.1
flushreturns only once every record accepted before it is written. - AC-7.2 Destroying the log system writes everything accepted, with
no
flushcall. - AC-7.3 Destroying an asynchronous sink writes what is still in its queue before its thread stops.
UC-4 A destination fails.
- AC-8.1 A sink that throws does not stop the other sinks, nothing reaches the caller, and the failure is counted. The same holds for a message function that throws, and for a failing flush.
- AC-8.2 A file that cannot be written (a full disk) fails the write whose line it was, and that failure is counted at once. Once the disk has room, the next write opens the file again and succeeds.
Invariants
Section titled “Invariants”Each invariant names the code that keeps it. See Invariants.
- INV-1 Nothing is lost without being counted. For each
asynchronous sink,
accepted + droppedequals the records offered to it, and when a flush returns,written + failedis at least theacceptedcount read when the flush began (equal to it if no one logged meanwhile). Kept byAsyncSink::writeandAsyncSink::run, which change the counts under the same lock as the queue. - INV-2 The queue is bounded. An asynchronous sink’s queue never
holds more than
capacityrecords. Kept byAsyncSink::write, which checks the size and waits or drops under the lock. - INV-3 Order and once. Records one thread logs reach a sink once each, in that thread’s order. Kept by the single FIFO queue and the single worker.
- INV-4 One record, one line. Each record becomes exactly one line,
lines from different threads never mix, and no character in a
message can end the line. Kept by
escape_controland by each sink writing a whole line under its own lock. - INV-5 Flush means written. When
flushreturns, every record accepted before the call has been written or has failed. Kept byAsyncSink::flush, which waits for a target it reads on entry. - INV-6 No exception reaches the caller. Kept by
Logger::log,LogSystem::dispatch, andLogSystem::flush, which catch and count. - INV-7 Lifetimes. The log system outlives every component that holds
one of its loggers; a sink’s target (a stream, a
Captured) outlives the sink; an asynchronous sink’s thread stops before the sink it writes to is destroyed. Kept by declaration order inmain, and inAsyncSinkby starting the thread in the constructor’s body and joining it in the destructor’s body.
Entities and relationships
Section titled “Entities and relationships”The nouns from the answers: service, component, logger, name, level, message, line, time, console, file, disk, destination, format, queue, thread, shutdown, failure, test. Filtered:
- Logger is a named source of records with a level. Components hold
one. Becomes
Logger. - Level is one of four ordered values. Becomes
enum class Level. - Record is one log statement, complete: level, logger name,
message, time. A value, copied freely. Becomes
struct Record. - Destination is where records go. The console, the file, and the
tests’ memory are all “something that takes a record”. Becomes the
Sinkinterface withStreamSink,FileSink, andMemorySink. - Format turns a record into a line. It has no state. Becomes a
function type,
Formatter, not a class. - Queue and thread belong to the slow destination, not to the
logger. Becomes
AsyncSink, a sink that wraps another sink. - Line is the formatter’s output, a
std::string. Time comes from aClock, a function the system calls. - The whole library needs an owner for the sinks and the loggers.
Becomes
LogSystem, made inmain. - Failure is a count on the system and on each asynchronous sink.
- Service, component, test: callers. They see a
Logger&.
Text description of the diagram
Sink is an interface with write and flush. StreamSink, FileSink, MemorySink, and AsyncSink each implement it. StreamSink refers to an output stream it does not own; FileSink owns its file; MemorySink refers to a Captured object it does not own. AsyncSink owns exactly one other Sink, the one it writes to, plus a queue of records, its counts, and a worker thread. LogSystem owns a list of Routes, each of which owns one Sink and holds the lowest level that sink wants. LogSystem also owns every Logger, kept in a map by name, a clock, and a failure count. Each Logger has a name and an atomic level, and refers back to the LogSystem that made it, without owning it.
Diagram source (Mermaid)
classDiagram
class Sink {
<<interface>>
+write(const Record&) void*
+flush() void*
}
class StreamSink {
-ostream& out_
-Formatter format_
}
class FileSink {
-ofstream out_
-Formatter format_
}
class MemorySink {
-Captured& into_
}
class AsyncSink {
-unique_ptr~Sink~ inner_
-deque~Record~ queue_
-AsyncStats stats_
-jthread worker_
+stats() AsyncStats
}
class Route {
+unique_ptr~Sink~ sink
+Level min
}
class LogSystem {
-vector~Route~ routes_
-map loggers_
-Clock clock_
-atomic failures_
+logger(string_view name) Logger&
+flush() void
+failures() uint64_t
}
class Logger {
-string name_
-atomic~Level~ level_
-LogSystem& system_
+log(Level, message) void
+set_level(Level) void
}
Sink <|.. StreamSink
Sink <|.. FileSink
Sink <|.. MemorySink
Sink <|.. AsyncSink
AsyncSink *-- "1" Sink : inner_ (owns)
LogSystem *-- "*" Route : routes_ (owns)
Route *-- "1" Sink : sink (owns)
LogSystem *-- "*" Logger : loggers_ (owns)
Logger --> LogSystem : system_ (refers to)Ownership runs one way, from main down: main owns the LogSystem,
which owns the routes and the loggers; each route owns a sink; an
AsyncSink owns the sink it writes to. The only reference pointing
back up is Logger::system_, and INV-7 says the system outlives every
logger, which is true because the system owns them.
Class design
Section titled “Class design”The design below is step 1 of the example, the complete answer to FR-1 … FR-7. Fields, JSON, and rotation are added in When the requirements change.
Records, levels, and time
Section titled “Records, levels, and time”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// How serious a record is. The names are declared from least to most// serious, and an enum class compares by that order, so "at or above warn"// is the plain comparison `level >= Level::warn`. (enum class keeps the// names inside the type, so you write Level::warn, and stops a Level from// being mixed up with an int.)enum class Level { debug, info, warn, error };
// The name a line shows for a level, such as "WARN". A string_view is a// read-only view of characters stored elsewhere (here, string literals// that live for the whole program), so nothing is copied.std::string_view to_string(Level level) noexcept;
// Milliseconds since 1970 in UTC, the precision the log lines show.// `using` gives a long type a short name. sys_time means "a point on the// system clock", which C++20 defines as UTC, and the milliseconds part// fixes the unit, so the type itself says "UTC, to the millisecond".using Timestamp = std::chrono::sys_time<std::chrono::milliseconds>;
// Where the time comes from. main passes the system clock; tests pass a// fixed or stepping one, so every line they check is predictable. Every// thread that logs calls it, with no lock, so it must be safe to call// from several threads at once (system_now is). std::function<Timestamp()>// holds anything that can be called with no arguments and returns a// Timestamp: a plain function such as system_now, or a lambda.using Clock = std::function<Timestamp()>;// The real clock: the current UTC time, cut down to whole milliseconds.Timestamp system_now();
// One log statement, complete: a sink needs nothing else to write it.// A plain struct (an aggregate) with no behaviour. It owns its strings by// value, so a copy is independent of the logger that made it: an async// sink can keep a copy and write it later, on another thread.struct Record { Level level = Level::info; std::string logger; // the name of the logger that made it std::string message; Timestamp time{}; // `{}` starts it at zero: 1970-01-01 00:00:00.000};Level is an enum class declared in order, so “at or above warn” is
level >= Level::warn. Timestamp is a sys_time in milliseconds, so
the type says both “UTC” and “the precision a line shows”. Clock is a
std::function: main passes the system clock, and a test passes a
lambda that returns a fixed time. That one choice makes every line a
test checks predictable (NFR-4).
Record is a plain aggregate with no behaviour. A sink needs nothing
else to write a record, which is what lets an asynchronous sink copy it
and write it later, on another thread, after the logger has moved on.
Sinks and formatters
Section titled “Sinks and formatters”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Somewhere records go: the console, a file, memory, a queue. The log// system holds every sink through this interface, so it never needs to// know which kind it has. A class with `= 0` functions (pure virtual) is// abstract: you cannot make a plain Sink, only a class derived from it// that supplies write and flush.class Sink {public: Sink() = default; // A sink holds a mutex, a stream, or a thread: copying one would make // no sense, so copying is forbidden (= delete). Sink(const Sink&) = delete; Sink& operator=(const Sink&) = delete; // virtual, so destroying a sink through a Sink pointer (as the // unique_ptr in a Route does) runs the derived class's destructor too. virtual ~Sink() = default;
// Contract for every sink: // - write and flush may be called from several threads at once, so a // sink protects its own state; // - write puts the whole line in its destination or throws; when it // throws, part of the line may be there already (a disk that filled // up mid-line), and a later write may work again; // - a sink never logs through the log system it serves. virtual void write(const Record& record) = 0; virtual void flush() = 0;};The interface is two functions, but the comment is the real contract. Every sink may be called from several threads at once, so it protects its own state; a write is whole or throws; and a sink never logs through the system it serves (see Concurrency and shutdown for why).
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A formatter has no state and one job, so it is a function, not a class.// Formatter is a std::function: it can hold any function or lambda that// takes a record (read only) and returns its line of text, without the// newline. Each sink is given one, so two sinks can format the same// record differently. format_line and format_short below both fit.using Formatter = std::function<std::string(const Record&)>;
// "2026-03-01 09:00:00.250 WARN payments: card declined"// For files: everything, in fixed-width columns.std::string format_line(const Record& record);
// "WARN payments: card declined"// For a person watching a console.std::string format_short(const Record& record);
// "2026-03-01 09:00:00.250", always in UTC, whatever the machine's own// time zone is.std::string format_time(Timestamp time);
// The message with every character below 0x20 written as an escape, so a// message can never start a new line of its own (see the CS-04 page).// A backslash is doubled too, so a reader can tell a real "\n" escape// from a message that happened to contain a backslash and an n. Every// other character, including bytes of 0x80 and above (UTF-8 letters), is// copied as it is.std::string escape_control(std::string_view text);A formatter is a std::function from a record to a string. Each sink is
given one, so the console and the file can format the same record
differently without the record knowing. StreamSink::write shows the
order that matters:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Writes one record as one whole line. Throws whatever the formatter// throws (std::bad_alloc, for example); the caller, LogSystem::dispatch// (or AsyncSink's worker, when this sink sits behind one), catches it and// counts it. The stream's own error state is not checked,// so a stream that has failed loses the line silently; FileSink checks.void StreamSink::write(const Record& record) { // Build the complete line, newline included, before taking the lock: // formatting allocates and may be slow, and other threads should not // wait for it. const std::string line = format_(record) + '\n'; // formatted before the lock // lock_guard locks mutex_ here and unlocks it when `lock` is destroyed // at the closing brace, on every way out of the function (RAII). const std::lock_guard lock(mutex_); out_ << line; // one string under the lock, so lines never interleave}Format first, then lock, then write one string. Formatting allocates and
can be slow; doing it before the lock keeps the lock short. Writing the
whole line, newline included, as one << under the lock is what keeps
lines from interleaving (INV-4).
Loggers
Section titled “Loggers”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A named source of records, such as "payments". Made and owned by a// LogSystem; components hold a Logger& that the system outlives.// A logger has its own level: a record below it is thrown away at once,// before any record is built. Every member function may be called from// several threads at once.class Logger {public: Logger(std::string name, Level level, LogSystem& system); // Not copyable: there is one logger per name, and components share it // by reference. Logger(const Logger&) = delete; Logger& operator=(const Logger&) = delete;
const std::string& name() const noexcept { return name_; } // The level is atomic, so one thread may change it while others read // it without a data race. memory_order_relaxed asks only for that: the // level is a lone setting, and no other data is published along with // it, so no stronger (slower) ordering is needed. Level level() const noexcept { return level_.load(std::memory_order_relaxed); } void set_level(Level level) noexcept { level_.store(level, std::memory_order_relaxed); } // True if a record at `level` would be kept. `this->level()` is the // member function; plain `level` here is the parameter. bool enabled(Level level) const noexcept { return level >= this->level(); }
// Logging never throws into the caller. A failure is counted by the // system (LogSystem::failures) and the record is lost. void log(Level level, std::string_view message) noexcept;
// The message is built only if the level is enabled: // log.debug([&] { return "cart " + cart.describe(); }); // `template <std::invocable F>` accepts any type F that can be called // with no arguments (a lambda, usually). A string literal is not // callable, so it skips this overload and uses the one above. // F&& with a template parameter is a forwarding reference: it binds to // any argument, temporary or not, without copying it. template <std::invocable F> void log(Level level, F&& make_message) noexcept { if (!enabled(level)) return; // the lambda is never called try { // std::invoke calls make_message; std::forward passes it on // exactly as the caller gave it. Whatever it returns (a string, // or a literal) is turned into a std::string. The call is inside // the try, so an exception from the lambda is caught too. submit(level, std::string(std::invoke(std::forward<F>(make_message)))); } catch (...) { // `...` catches an exception of any type note_failure(); } }
// Shorthands: log.warn(m) is log(Level::warn, m). M is whatever the // caller passed (a string or a lambda), forwarded unchanged, so the // overload choice above still happens. template <typename M> void debug(M&& m) noexcept { log(Level::debug, std::forward<M>(m)); } template <typename M> void info(M&& m) noexcept { log(Level::info, std::forward<M>(m)); } template <typename M> void warn(M&& m) noexcept { log(Level::warn, std::forward<M>(m)); } template <typename M> void error(M&& m) noexcept { log(Level::error, std::forward<M>(m)); }
private: void submit(Level level, std::string message); // may throw; log catches void note_failure() noexcept;
const std::string name_; std::atomic<Level> level_; // read by every log call, changed at any time LogSystem& system_; // not owned: the system owns this logger, and outlives it};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The plain form: the message is already text. noexcept, so nothing may// escape: every exception inside is caught and counted, and the record is// lost. (A string the caller builds before the call is built in the// caller's code, outside this promise.)void Logger::log(Level level, std::string_view message) noexcept { if (!enabled(level)) return; // one atomic load, then nothing try { // The string_view only points at the caller's characters; the // record needs its own std::string, which may throw bad_alloc. submit(level, std::string(message)); } catch (...) { note_failure(); }}
// Builds the record and hands it to the system. Shared by both forms of// log, which catch anything it throws (from the clock, or a copy).void Logger::submit(Level level, std::string message) { // Brace initialisation fills the Record's members in declaration // order: level, logger name (copied), message (moved in, because this // function owns its copy and does not need it again), time from the // system's clock. const Record record{level, name_, std::move(message), system_.now()}; system_.dispatch(record);}A Logger has a name, a level, and a reference to its system. Its
level is a std::atomic<Level>, because any thread can read it while
another changes it. There are two ways to log:
log.info("charged order 41"): the message is a string. If the level is off, the call does one atomic load and returns. The caller has still built the string, though.log.debug([&] { return "cart " + cart.describe(); }): the message is a function. It is called only if the level is on, so a disabled debug line costs nothing to build (AC-4.1).
The template is constrained by std::invocable, so a string literal
never matches it: a const char[N] is not callable and goes to the
string_view overload.
Both forms are noexcept, and both catch everything inside. The
lambda’s own exceptions are caught too, because the lambda runs inside
the try. A string the caller builds is different: if
"charged order " + std::to_string(order) throws std::bad_alloc, it
throws in the caller’s code, before log is entered. The library can
promise only what happens inside its own functions.
The log system
Section titled “The log system”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A sink and the lowest level it wants. unique_ptr means the route owns// the sink: when the route is destroyed, so is the sink. The pointer is// to the Sink base class, so a route can hold any kind of sink.struct Route { std::unique_ptr<Sink> sink; Level min = Level::debug; // records below this level skip this sink};
// Owns the sinks and the loggers. main makes one and passes Logger& to// the components that need one; there is no global instance.class LogSystem {public: // The routes are fixed here and never change, so reading them needs no // lock. Throws std::invalid_argument for a missing sink or clock. // The vector is taken by value and moved in: a unique_ptr cannot be // copied, so the caller passes the routes with std::move or as a // temporary. `clock = system_now` is a default argument. explicit LogSystem(std::vector<Route> routes, Clock clock = system_now, Level default_level = Level::info);
// Flushes every sink; then the sinks are destroyed, and an async sink // writes everything it accepted before its thread stops. ~LogSystem(); LogSystem(const LogSystem&) = delete; LogSystem& operator=(const LogSystem&) = delete;
// The logger with this name, made on first use at the default level. // Thread safe. The reference stays valid for the life of the system. Logger& logger(std::string_view name);
void flush() noexcept; std::uint64_t failures() const noexcept { return failures_.load(); }
private: // `friend` lets Logger call these private functions: only a logger // may dispatch a record or count a failure. friend class Logger; Timestamp now() const { return clock_(); } void dispatch(const Record& record) noexcept; // fetch_add(1) adds one atomically, so two threads counting at once // never lose a count. void note_failure() noexcept { failures_.fetch_add(1); }
const std::vector<Route> routes_; const Clock clock_; const Level default_level_; std::mutex loggers_mutex_; // Name to logger. A map element never moves once added, so a Logger& // stays valid. std::less<> (with empty brackets) lets find look up a // std::string_view without first building a std::string from it. std::map<std::string, Logger, std::less<>> loggers_; // map nodes never move std::atomic<std::uint64_t> failures_{0};};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Gives the record to every sink that wants it, in the order the routes// were given. Reads routes_ with no lock: they never change after the// constructor. A sink that throws loses only its own line; the rest still// get the record.void LogSystem::dispatch(const Record& record) noexcept { for (const Route& route : routes_) { if (record.level < route.min) continue; // below this sink's level: skip it try { route.sink->write(record); } catch (...) { note_failure(); // the other sinks still get the record } }}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Find the logger with this name, or make it. The lock makes "look, then// add" one step, so two threads asking for a new name at once get the// same logger, not two. Throws std::bad_alloc if memory runs out.Logger& LogSystem::logger(std::string_view name) { const std::lock_guard lock(loggers_mutex_); // `found` is an iterator: a position in the map, or end() for "none". auto found = loggers_.find(name); if (found == loggers_.end()) { // try_emplace(key, args...) builds the Logger in place inside the // map, from (name, default level, this system). That matters: a // Logger cannot be copied or moved. It returns a pair of (iterator, // inserted?); .first keeps the iterator. found = loggers_.try_emplace(std::string(name), std::string(name), default_level_, *this) .first; } // found->second is the Logger part of the map entry (first is the // name). The reference stays valid while the system lives, because a // map never moves its elements. return found->second;}LogSystem owns the routes and the loggers.
- The routes are
constand set in the constructor. After that, every thread reads them and none writes, so reading them needs no lock. That is the reason “no sinks added later” was worth asking about: allowing it would put a lock (or something cleverer) on every log call. - The loggers live in a
std::map. Astd::mapnever moves its nodes, so theLogger&thatlogger()returns stays valid while other loggers are added. Astd::vector<Logger>would move its elements when it grows, and in fact it does not compile here at all:Logger’s copy constructor is deleted (and it holds an atomic), so it has no copy or move constructor, and GCC 11 rejectsemplace_backwith “result type must be constructible from value type of input range”. logger()takes a lock. It is meant to be called once, when a component is made, not on every log call. A component keeps theLogger&.dispatchis a loop, not a chain. Every route whose lowest level the record reaches gets the record. A sink that throws is counted, and the loop goes on to the next sink (AC-8.1).
class LogSystem
made in main; owns the sinks and the loggers
Data members
const std::vector<Route> routes_;owned; fixed at construction, read without a lockconst Clock clock_;owned; main passes system_now, tests a lambdastd::mutex loggers_mutex_;guards loggers_ onlystd::map<std::string, Logger, std::less<>> loggers_;owned; nodes never movestd::atomic<std::uint64_t> failures_;every caught failure
Member functions
Logger& logger(std::string_view name);made on first use; valid for the system's lifevoid flush() noexcept;std::uint64_t failures() const noexcept;void dispatch(const Record& record) noexcept;private: every sink at or above its min
class Logger
owned by the system; components hold a Logger&
Data members
const std::string name_;std::atomic<Level> level_;relaxed loads; changed at any timeLogSystem& system_;not owned; outlives the logger
Member functions
void log(Level level, std::string_view message) noexcept;void log(Level level, F&& make_message) noexcept;built only if enabledvoid set_level(Level level) noexcept;
struct Route
Data members
std::unique_ptr<Sink> sink;ownedLevel min;the lowest level this sink wants
class AsyncSink
a Sink that owns a Sink and a thread
Data members
const std::unique_ptr<Sink> inner_;owned; only the worker writes to itconst std::size_t capacity_;const Level wait_from_;at or above: wait for room; below: dropstd::mutex mutex_;guards queue_, stats_, closing_std::condition_variable has_work_;the worker waits herestd::condition_variable progress_;writers wanting room, and flush, wait herestd::deque<Record> queue_;AsyncStats stats_;bool closing_;std::jthread worker_;started in the constructor body, joined in the destructor body
Member functions
void write(const Record& record) override;void flush() override;AsyncStats stats() const;void run();private: the worker's loop
The asynchronous sink
Section titled “The asynchronous sink”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Counters an AsyncSink keeps, so a test or an operator can see what// happened to the records. stats() returns a copy of all six, taken under// the lock, so the numbers agree with each other. Once the worker has// finished every accepted record, accepted == written + failed; dropped// records were never accepted.struct AsyncStats { std::uint64_t accepted = 0; // put in the queue std::uint64_t written = 0; // written by the inner sink std::uint64_t failed = 0; // the inner sink threw std::uint64_t dropped = 0; // refused because the queue was full std::size_t high_water = 0; // the most records ever waiting at once std::size_t waiting = 0; // writers waiting for room right now};
// A Decorator: it is a Sink, and it owns the Sink it passes records to.// After construction only the worker thread calls inner->write.// write copies the record into a bounded queue and returns; a background// thread (the worker) takes records off the queue in order and writes// them to the inner sink. `final` means no class may derive from it.class AsyncSink final : public Sink {public: // capacity: how many records may wait (at least 1). When the queue is // full, a record below `wait_from` is dropped and counted; a record at // or above it waits for room. Takes ownership of `inner` (the caller // passes it with std::move). Throws std::invalid_argument if inner is // null or capacity is 0. Starts the worker thread. AsyncSink(std::unique_ptr<Sink> inner, std::size_t capacity, Level wait_from = Level::error);
// Writes every record already accepted, then stops the worker. No // other thread may be calling write or flush by then. ~AsyncSink() override;
void write(const Record& record) override; // waits only as described above void flush() override; // returns once every record accepted before it is written AsyncStats stats() const;
private: void run();
const std::unique_ptr<Sink> inner_; // owned; destroyed with the AsyncSink const std::size_t capacity_; const Level wait_from_;
// One mutex guards queue_, stats_, and closing_ (the condition // variables need no guard of their own). `mutable` lets the const // function stats() lock it. mutable std::mutex mutex_; std::condition_variable has_work_; // the worker waits here std::condition_variable progress_; // writers wanting room, and flush, wait here std::deque<Record> queue_; // oldest at the front; never more than capacity_ AsyncStats stats_; bool closing_ = false; // set by the destructor: finish the queue, then stop
// std::jthread is a thread object that joins (waits for its thread to // finish) when it is destroyed, so it can never be left running. It // is declared last, so it would be the first member destroyed; the // destructor joins it explicitly before that anyway. std::jthread worker_; // started in the constructor body, once every member above exists};AsyncSink is a sink, so the log system does not know or care that it
is asynchronous. It owns the sink it writes to, so it is a
Decorator: it adds a queue and a thread to any
sink, without that sink changing. The file sink is just as testable on
its own, and the queue is just as testable over a memory sink.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Called by any thread that logs. Puts a copy of the record in the queue// and returns without writing it. If the queue is full: a record below// wait_from_ is dropped (counted, and write returns at once); a record at// or above it waits until the worker makes room. Throws only if memory// runs out, copying the record or growing the queue.void AsyncSink::write(const Record& record) { // The caller's record is gone once write returns, so the queue needs // its own copy. Copying allocates the strings, which is done before // the lock so other threads are not kept waiting for it. Record copy = record; // the allocation happens before the lock // unique_lock, not lock_guard, because a condition variable's wait // must be able to unlock and relock it, and because it is unlocked // by hand below. std::unique_lock lock(mutex_); if (queue_.size() >= capacity_) { if (record.level < wait_from_) { ++stats_.dropped; return; // `lock` is destroyed here, which unlocks the mutex } ++stats_.waiting; // wait(lock, condition) unlocks the mutex while it sleeps, and // relocks it before checking the condition again, so the worker can // take the lock and pop. It returns only when the condition is // true, which also covers a wake-up that nothing asked for. progress_.wait(lock, [&] { return queue_.size() < capacity_; }); --stats_.waiting; } // std::move hands the copy's strings to the queue instead of copying // them a second time; `copy` is not used again. queue_.push_back(std::move(copy)); ++stats_.accepted; stats_.high_water = std::max(stats_.high_water, queue_.size()); // Unlock before waking the worker, so it does not wake up only to // find the mutex still held. lock.unlock(); has_work_.notify_one(); // one worker, so waking one is enough}Text description of the diagram
AsyncSink::write first copies the record, before taking the lock. Then it takes the lock and checks whether the queue is full. If it is not full, the record is pushed and the accepted count goes up by one. If the queue is full and the record’s level is below wait_from, the dropped count goes up by one and write returns without waiting. If the queue is full and the level is at or above wait_from, write waits on the progress_ condition variable until there is room, then pushes the record. After pushing, it releases the lock and wakes the worker.
Diagram source (Mermaid)
flowchart TD
start[write a record] --> copy[copy the record, before the lock]
copy --> lock[take the lock]
lock --> full{queue full?}
full -->|no| push[push it, accepted plus 1]
full -->|yes| level{level below wait_from?}
level -->|yes| drop[dropped plus 1, return]
level -->|no| wait[wait for room on progress_]
wait --> push
push --> notify[unlock, then wake the worker]VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The worker thread's whole life: started by the constructor, it loops// until the destructor sets closing_ and the queue is empty. Each turn of// the loop takes the oldest record, writes it with the mutex unlocked,// then relocks to count the result. It never throws: a failed write is// caught and counted, and the loop goes on.void AsyncSink::run() { std::unique_lock lock(mutex_); // held except while waiting and around the write for (;;) { // a loop with no condition; the only way out is the return // Sleep, with the mutex unlocked, until there is a record or the // sink is closing; wake holding the mutex again. has_work_.wait(lock, [&] { return !queue_.empty() || closing_; }); if (queue_.empty()) return; // closing, and everything accepted is written
// Move the oldest record out of the queue into a local variable, so // it can be written after the mutex is released. The moved-from // front element is then removed. Record next = std::move(queue_.front()); queue_.pop_front(); lock.unlock(); // from here, writers can push again while we write progress_.notify_all(); // room for one more
bool ok = true; // did the inner sink write it? try { inner_->write(next); // the slow part, outside the lock } catch (...) { ok = false; // counted; the worker carries on with the next record }
lock.lock(); // the counters are shared, so count under the lock // `?:` picks which counter, written or failed, and ++ adds one to it. ++(ok ? stats_.written : stats_.failed); progress_.notify_all(); // for flush } // back to the top with the mutex held, as wait expects}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Waits until every record accepted before the call has been handled by// the worker (written or failed), then flushes the inner sink. Records// accepted after the call started are not waited for, so a flush cannot// be kept waiting forever by threads that go on logging. May throw what// the inner sink's flush throws.void AsyncSink::flush() { std::unique_lock lock(mutex_); // Records are handled in queue order, so once written + failed reaches // the accepted count seen now, every one of those records is done. const std::uint64_t target = stats_.accepted; progress_.wait(lock, [&] { return stats_.written + stats_.failed >= target; }); lock.unlock(); inner_->flush(); // safe beside the worker: every sink is thread safe}
// Stops the worker without losing anything it accepted. closing_ is set// under the lock (the worker reads it under the same lock); the extra// braces make the lock_guard end before the notify.AsyncSink::~AsyncSink() { { const std::lock_guard lock(mutex_); closing_ = true; } has_work_.notify_one(); worker_.join(); // the worker drains the queue before it returns try { inner_->flush(); } catch (...) { // A destructor must not throw; there is nowhere left to report it. }}How this code works: AsyncSink: write, run, and flush working together
Three kinds of thread meet in one AsyncSink: the threads that log (in
write), the one worker (in run), and whoever calls flush. They share
queue_ and stats_, so each touches them only while holding mutex_.
Two condition variables let a thread sleep until something changes:
has_work_wakes the worker when a record is pushed, or when the destructor setsclosing_;progress_wakes writers waiting for room (after a pop) and flush (after a record is counted).
wait(lock, condition) checks the condition first. If it is false, it
unlocks the mutex and sleeps, and on waking it locks again and checks
again. So code after a wait always runs with the mutex held and the
condition true.
A trace. These are the values of test ac_6_2: capacity 2,
wait_from left at error, and an inner sink (the gate) that holds the
worker inside its first write until the test opens it.
| Step | Thread | What happens | Queue after | accepted | dropped | written |
|---|---|---|---|---|---|---|
| 1 | test | write(r1): room, push, wake the worker |
r1 |
1 | 0 | 0 |
| 2 | worker | pops r1, unlocks, is held inside the gate |
empty | 1 | 0 | 0 |
| 3 | test | write(r2): room, push |
r2 |
2 | 0 | 0 |
| 4 | test | write(r3): room, push; high_water becomes 2 |
r2, r3 |
3 | 0 | 0 |
| 5 | test | write(r4), info: full, and info is below error |
r2, r3 |
3 | 1 | 0 |
| 6 | test | write(r5), warn: full, and warn is below error |
r2, r3 |
3 | 2 | 0 |
| 7 | test | opens the gate, then flush(): target is 3 |
r2, r3 |
3 | 2 | 0 |
| 8 | worker | finishes r1, locks, counts it, wakes progress_ |
r2, r3 |
3 | 2 | 1 |
| 9 | worker | pops and writes r2, then r3, counting each |
empty | 3 | 2 | 3 |
| 10 | test | flush wakes: written + failed is 3, at least 3 |
empty | 3 | 2 | 3 |
Up to step 6 the order is fixed, because the test waits until the
worker is inside the gate. From step 7 on, the worker and the test run
at the same time, so steps 8 and 9 may happen before flush reads its
target; the target is 3 either way, and flush returns only after
step 9.
Steps 2 and 3 show the point of writing outside the lock: the worker is
stuck inside a slow write, and the test can still push r2 and r3, and
have r4 and r5 dropped, without waiting. If r4 had been an error,
step 5 would instead have gone to sleep on progress_ (with waiting
at 1) until the worker’s pop in step 9 made room. That is test ac_6_3.
Stopping. The destructor sets closing_ under the lock and wakes the
worker. The worker’s wait returns when the queue is not empty or
closing_ is set, but it returns from run only if the queue is also
empty. So a closing sink still writes every record it accepted; only
then does join return, and only then is the inner sink flushed and,
with the AsyncSink, destroyed.
Three details carry the design:
- The worker writes outside the lock. It takes a record off the queue, unlocks, writes, and locks again to count. While the file is slow, other threads can still put records in the queue (or be dropped) without waiting for the file. Building it step by step shows what happens otherwise.
flushwaits for a target, not for an empty queue. It readsacceptedwhen it is called and waits untilwritten + failedreaches it. Records are written in queue order, so that moment means every record accepted before the call is done (INV-5). Waiting for “the queue is empty” instead could wait forever in a busy program, because other threads keep adding records.- The destructor drains. It sets
closing_, wakes the worker, and joins it. The worker returns only when the queue is empty andclosing_is set, so everything accepted is written first (AC-7.3). What keeps the thread from touching a member that is not there yet, or no longer there, is that it is started in the constructor’s body, when every member exists, and joined in the destructor’s body, before any member is destroyed.worker_is also declared last, which is a defensive habit: it would matter if someone moved the start into the member initializer list.
Where each rule lives
Section titled “Where each rule lives”| Rule | Where it lives |
|---|---|
| A record below the logger’s level is not made | Logger::enabled, first line of Logger::log |
| A sink gets only records at or above its minimum | LogSystem::dispatch |
| A message cannot end the line | escape_control, called by both formatters |
| Lines never interleave | each sink’s write, one string under its lock |
The queue is bounded; below wait_from is dropped |
AsyncSink::write |
| Everything accepted is written before the thread stops | AsyncSink::run (returns only when empty) and ~AsyncSink |
| Flush covers what was accepted before it | AsyncSink::flush |
| No exception reaches the caller | Logger::log, LogSystem::dispatch, LogSystem::flush |
| Every failure is counted | LogSystem::note_failure, AsyncStats::failed |
Verification trace
Section titled “Verification trace”Take the step 1 demo: a console route at warn with format_short,
and an asynchronous file route at debug with format_line. The
payments logger is at info. PaymentService calls
log_.warn("card declined for order 42"):
Logger::logloads the level,info.warn >= info, so it goes on.submitbuilds aRecordwith the namepayments, the level, the message, and the time from the clock.dispatchloops over the routes. Console:warn >= warn, soStreamSink::writeformatsWARN payments: card declined for order 42, locks, and writes it tostd::cout.- File:
warn >= debug, soAsyncSink::writecopies the record, locks, finds room (64), pushes it, unlocks, and wakes the worker. The call returns; the payment thread is done. - Later, on the worker thread:
runpops the record, unlocks, and calls the innerStreamSink::write, which formats the full line with the time and writes it. The worker locks again and counts it as written.
Nothing in steps 1 to 4 waited for the file.
Text description of the diagram
PaymentService calls warn on the payments logger. The logger’s level is info, so the warning passes. The logger takes the time from the log system’s clock and asks the system to dispatch the record. The system writes it to the console StreamSink, because warn reaches that sink’s minimum of warn; the console sink writes one short line under its own lock. The system then gives the record to the AsyncSink, because warn reaches its minimum of debug. The AsyncSink copies the record, locks, pushes it onto its queue, unlocks, wakes its worker, and returns at once. The call returns to PaymentService with nothing thrown. Later, the worker thread wakes, pops the record, unlocks, and writes it to the file StreamSink outside the lock. When that write is done, the worker locks again, adds one to the written count, and wakes anything waiting in flush.
Diagram source (Mermaid)
sequenceDiagram
participant P as PaymentService
participant L as Logger payments
participant S as LogSystem
participant C as console StreamSink
participant A as AsyncSink
participant W as worker thread
participant F as file StreamSink
P->>L: warn(card declined for order 42)
L->>L: level is info, warn passes
L->>S: now(), then dispatch(record)
S->>C: write(record), warn reaches warn
C-->>S: one short line written under its lock
S->>A: write(record), warn reaches debug
A->>A: copy, lock, push, unlock, wake worker
A-->>S: returns at once
S-->>L: done
L-->>P: returns, nothing thrown
W->>A: wake, pop the record, unlock
W->>F: write(record), outside the lock
F-->>W: full line written
W->>A: lock, written plus 1, wake flush waitersArchitecture and patterns
Section titled “Architecture and patterns”Where does the log system live?
Section titled “Where does the log system live?”Is this a Chain of Responsibility?
Section titled “Is this a Chain of Responsibility?”No. In a Chain of Responsibility,
a request goes along the chain until one handler takes it, and the rest
never see it. Here every sink whose lowest level the record reaches
gets it. That is a fan-out, and a loop over a const vector says so
directly. A chain would make the order of sinks matter and would let
one sink decide for the others, neither of which the team wants.
AsyncSink is a Decorator: same interface,
owns the thing it wraps, adds behaviour around it. Decorators also
stack: a sink that adds a prefix, wrapped in an AsyncSink, works with
no change to either.
Formatters: a class or a function?
Section titled “Formatters: a class or a function?”When the queue is full
Section titled “When the queue is full”Lazy messages: lambdas or macros?
Section titled “Lazy messages: lambdas or macros?”Why noexcept, and where do failures go?
Section titled “Why noexcept, and where do failures go?”What is not here, and why
Section titled “What is not here, and why”- No logger hierarchy.
http.clientdoes not inherithttp’s level. The team did not ask for it; it would replace the map lookup with a walk up the name. - No sinks added or removed while running. Fixed routes are what make
dispatchlock-free to read. - No configuration file.
mainis the configuration. - No asynchronous console. The console route is synchronous: a
person is watching it, and it gets only warnings and errors. If it
became slow, wrapping it in an
AsyncSinkis one line inmain.
Building it step by step
Section titled “Building it step by step”The example has two steps:
step-1: loggers, levels, sinks, formats, the asynchronous sink, and failures (FR-1 … FR-7).step-2: fields, JSON lines, and the rotating file, the change.
Step 1: a line that cannot lie
Section titled “Step 1: a line that cannot lie”Start with the formats, because they decide what a reader can trust. The first version writes the message as it is:
Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.
// The flaw: the message is copied into the line as it is. A newline in it// ends this line and starts another, which the attacker writes.std::string format_short(const Record& record) { return std::string(to_string(record.level)) + ' ' + record.logger + ": " + record.message; // not escaped}
void Auth::login(const std::string& user) { log_.info("login by " + user); // user comes from the request}A user who signs in with the name
bob\nERROR auth: admin password changed (with a real newline) gets
two lines in the log, and the second one looks exactly like a line the
program wrote. Anyone reading the log, or any alert that matches on
ERROR auth, is fooled. This is log injection. The corrected version
escapes every control character, and the backslash too, so that an
escape in the output always means one:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Returns a copy of the text that is safe to put on one line: every// character below 0x20 (newline, tab, and the other control characters)// becomes a visible escape, and a backslash becomes two backslashes.// Never fails except by running out of memory (std::bad_alloc).std::string escape_control(std::string_view text) { std::string out; out.reserve(text.size()); // usually the same length: grow the buffer once for (const char c : text) { // char may be signed, so a UTF-8 byte such as 0xC3 could read as a // negative number and pass `< 0x20` by mistake. As unsigned char it // is 0 to 255, and only the real control characters are below 0x20. const auto byte = static_cast<unsigned char>(c); if (c == '\\') { out += "\\\\"; // so an escape in the output always means one } else if (c == '\n') { // The two characters backslash and n, not a line break. In C++ // source a backslash inside quotes is written twice. out += "\\n"; } else if (c == '\r') { out += "\\r"; } else if (c == '\t') { out += "\\t"; } else if (byte < 0x20) { // Any other control character, as backslash, x, and two hex // digits: byte 0x1b (escape) becomes the four characters "\x1b". // snprintf writes into the small buffer, never past its size. char hex[8]; std::snprintf(hex, sizeof hex, "\\x%02x", static_cast<unsigned>(byte)); out += hex; } else { out += c; // an ordinary character: copied unchanged } } return out;}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The full line for a file: time, level, logger name, message. Both// formatters escape the message here, once, so no caller can forget to.// Only the message is escaped; the logger name is written as it is.std::string format_line(const Record& record) { std::string level(to_string(record.level)); // a string copy of the view level.resize(5, ' '); // pad with spaces to 5: "INFO " and "ERROR" line up return format_time(record.time) + ' ' + level + ' ' + record.logger + ": " + escape_control(record.message);}
// The short line for a console: no time, no padding. The std::string(...)// around to_string is needed because a string_view cannot be joined to a// char with +; once the left side is a std::string, each + appends.std::string format_short(const Record& record) { return std::string(to_string(record.level)) + ' ' + record.logger + ": " + escape_control(record.message);}How this code works: escape_control, one character at a time
escape_control reads the message one char at a time and builds a new
string. Each character goes down the if chain and takes the first
branch that matches:
- a backslash becomes two backslashes;
- newline, carriage return, and tab become
\n,\r, and\t: two visible characters each; - any other character below 0x20 becomes
\xand two hex digits; - everything else is copied unchanged.
The backslash is checked first, and doubled, so that the output can be
read back without doubt: a single backslash in the output always starts
an escape. Test ac_3_2 feeds it the six characters a, backslash,
n, carriage return, tab, and 0x1b:
| Input character | Branch | Output |
|---|---|---|
a |
ordinary | a |
| backslash | backslash | \\ |
n |
ordinary | n |
| carriage return | named control | \r |
| tab | named control | \t |
| 0x1b (escape) | other control, as hex | \x1b |
So the result is a\\n\r\t\x1b, all on one line. Without the first rule, the
input backslash and n would come out as \n, the same text as an
escaped newline, and a reader could not tell the two apart.
The formatters then call escape_control on the message only, so every
sink that uses them gets the protection, and no caller has to remember
it.
Now the same name gives one line, INFO auth: login by bob\nERROR auth: admin password changed, where \n is two visible
characters. Escaping in the formatter, not in each call, means no caller
can forget it.
The worker must not hold the lock while it writes
Section titled “The worker must not hold the lock while it writes”The first version of the worker is shorter, and wrong:
Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.
// Correct about order and counting, wrong about the lock: mutex_ is held// from the first line to the last, except while wait sleeps.void AsyncSink::run() { std::unique_lock lock(mutex_); for (;;) { has_work_.wait(lock, [&] { return !queue_.empty() || closing_; }); if (queue_.empty()) return; try { // The flaw: the mutex is still locked here. Every write() call // blocks on it until this slow write finishes, even one that // would only be dropped. inner_->write(queue_.front()); // the slow write, under the lock ++stats_.written; } catch (...) { ++stats_.failed; } queue_.pop_front(); // the record leaves the queue only after its write progress_.notify_all(); }}It holds mutex_ during the slow write. Every AsyncSink::write needs
the same mutex to push a record, so while the file takes a second, every
thread that logs to that file waits a second: the exact problem the
asynchronous sink was meant to solve. The “drop below error” rule never
even runs, because a writer cannot take the lock to see that the queue
is full.
This is not only a theory. Built into step 1 in place of the real
run, this version makes three tests hang: ac_6_2, ac_6_3, and
ac_7_3. Each holds the worker inside a slow write (the GateSink
in Tests) and then tries to write more, which needs the lock
the worker will not release until the test opens the gate. The other
tests pass, because their sinks are fast; a slow destination is what
exposes it.
The corrected version, shown above, moves the record out of the queue, unlocks, writes, and locks again only to count:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The worker thread's whole life: started by the constructor, it loops// until the destructor sets closing_ and the queue is empty. Each turn of// the loop takes the oldest record, writes it with the mutex unlocked,// then relocks to count the result. It never throws: a failed write is// caught and counted, and the loop goes on.void AsyncSink::run() { std::unique_lock lock(mutex_); // held except while waiting and around the write for (;;) { // a loop with no condition; the only way out is the return // Sleep, with the mutex unlocked, until there is a record or the // sink is closing; wake holding the mutex again. has_work_.wait(lock, [&] { return !queue_.empty() || closing_; }); if (queue_.empty()) return; // closing, and everything accepted is written
// Move the oldest record out of the queue into a local variable, so // it can be written after the mutex is released. The moved-from // front element is then removed. Record next = std::move(queue_.front()); queue_.pop_front(); lock.unlock(); // from here, writers can push again while we write progress_.notify_all(); // room for one more
bool ok = true; // did the inner sink write it? try { inner_->write(next); // the slow part, outside the lock } catch (...) { ok = false; // counted; the worker carries on with the next record }
lock.lock(); // the counters are shared, so count under the lock // `?:` picks which counter, written or failed, and ++ adds one to it. ++(ok ? stats_.written : stats_.failed); progress_.notify_all(); // for flush } // back to the top with the mutex held, as wait expects}How this code works: What changed in run, and why each change is needed
Put the two versions side by side and four things differ.
- The record is moved out before the write. The flawed version
writes
queue_.front()where it lies and pops it only afterwards, so the record is still inside the shared queue during the write. The corrected version moves the record into the local variablenextand pops it first, so during the write the worker uses only its own object, and other threads are free to change the queue. lock.unlock()comes before the write. This is the change that matters. While the file is slow,writecan take the lock, push or drop, and return.progress_is notified twice. Once right after the pop, because there is now room in the queue for a writer that is waiting; and once after counting, because aflushis waiting forwritten + failedto grow.- The count is made after locking again.
stats_is shared, so++(ok ? stats_.written : stats_.failed)must run under the lock. Thebool okcarries the result of the write from the unlocked part to the locked part.
One thing did not change: the worker still takes records strictly from
the front, one at a time, so they are written in the order they were
accepted. That order is what lets flush wait for a count instead of
for an empty queue.
Wiring it in main
Section titled “Wiring it in main”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A component gets the logger it needs. It does not know about sinks,// formats, or where the log system lives.// It keeps a reference, not a copy: the LogSystem owns the logger and// must outlive the service.class PaymentService {public: explicit PaymentService(Logger& log) : log_(log) {}
// A pretend charge: more than 500.00 is declined (a warning), anything // else succeeds (info). The ' in 50'000 only groups digits, like a // comma; it is the number 50000. bool charge(int order, int cents) { if (cents > 50'000) { // The message string is built here, in the caller, before warn // is entered, even if the level were off. log_.warn("card declined for order " + std::to_string(order)); return false; } log_.info("charged order " + std::to_string(order)); return true; }
private: Logger& log_; // not owned};PaymentService takes a Logger&. It does not include anything about
sinks or files, and its tests can give it a logger whose sink is a
Captured.
Scenarios
Section titled “Scenarios”The step 1 demo
Section titled “The step 1 demo”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
int main() { std::ostringstream file_text; // outlives the system that writes to it
// A clock that moves 250 ms per record, so the output is the same on // every run. A real program passes system_now, the default. This one // changes next with no lock, so it is safe only because one thread // logs here. // 2026y / March / 1 is a C++20 calendar date; sys_days turns it into a // point in time, and + 9h makes it 09:00 UTC. 250ms and 9h are // duration literals from std::chrono. Timestamp next = sys_days{2026y / March / 1} + 9h; // The lambda captures `next` by reference ([&next]), so each call // returns the current value and moves the shared variable on by 250 ms. Clock clock = [&next] { const Timestamp now = next; next += 250ms; return now; };
// The inner braces make a scope: everything made inside it is // destroyed at its closing brace, before the file text is printed. { // The file route: an AsyncSink that owns a StreamSink writing full // lines into file_text, with room for 64 waiting records. auto async = std::make_unique<AsyncSink>( std::make_unique<StreamSink>(file_text, format_line), 64); // A reference kept so main can read the stats later. std::move // below hands ownership to the routes; the object itself does not // move, so this reference still points at it. AsyncSink& file = *async; // valid while the system owns it
std::vector<Route> routes; // Each {sink, min} builds a Route. The console wants warn and up. routes.push_back({std::make_unique<StreamSink>(std::cout, format_short), Level::warn}); // `async` is empty after this move; the route owns the sink now. routes.push_back({std::move(async), Level::debug}); LogSystem logs(std::move(routes), clock); // the system owns both routes now
// Two loggers, made on first use at the default level, info. Logger& http = logs.logger("http"); PaymentService payments(logs.logger("payments"));
std::cout << "-- console: warnings and above\n"; payments.charge(41, 1'999); payments.charge(42, 80'000);
// A lazy message: `built` counts how many times the lambda ran, // which shows whether a disabled debug line was ever built. int built = 0; const auto describe = [&built] { ++built; return std::string("GET /cart took 12 ms"); }; http.debug(describe); // http is at info: the lambda is not called const int built_at_info = built; logs.logger("http").set_level(Level::debug); // the same logger http.debug(describe); // now enabled: called once, and logged
// A message with a real newline in it; the formatters escape it. logs.logger("payments").error("refund failed for order 40\nINFO payments: refund ok");
// Wait for the worker to write everything accepted so far, so the // stats below are final. logs.flush(); const AsyncStats s = file.stats(); std::cout << "-- debug message built " << built_at_info << " time(s) at INFO, " << built - built_at_info << " at DEBUG\n"; std::cout << "-- async sink: accepted " << s.accepted << ", written " << s.written << ", dropped " << s.dropped << ", failed " << s.failed << '\n'; std::cout << "-- log failures: " << logs.failures() << '\n'; } // payments, then logs: sinks flushed, the async sink's thread stopped
std::cout << "-- the file: everything, full format\n" << file_text.str();}-- console: warnings and aboveWARN payments: card declined for order 42ERROR payments: refund failed for order 40\nINFO payments: refund ok-- debug message built 0 time(s) at INFO, 1 at DEBUG-- async sink: accepted 4, written 4, dropped 0, failed 0-- log failures: 0-- the file: everything, full format2026-03-01 09:00:00.000 INFO payments: charged order 412026-03-01 09:00:00.250 WARN payments: card declined for order 422026-03-01 09:00:00.500 DEBUG http: GET /cart took 12 ms2026-03-01 09:00:00.750 ERROR payments: refund failed for order 40\nINFO payments: refund okHow to read it:
- Order 41 is charged at
info; it is not on the console, which wantswarnand above (AC-2.1). Order 42 is declined atwarnand appears in the short format. - The HTTP debug line is a lambda. At
infoit is not built (0 times); afterset_level(Level::debug)on the same logger, it is built once and logged (AC-1.3, AC-4.1).logs.logger("http")returned the same logger ashttp(AC-1.2). - The refund error has a newline in its message. On the console and in
the file it is one line with a visible
\n(AC-3.2). - The asynchronous sink accepted 4 records and wrote 4, with nothing dropped: the queue holds 64.
- The file text is printed after the system is destroyed, and it has all four records with times 250 ms apart from the demo’s clock (AC-7.2). The console lines appear first because they were written at once; the file lines were written by the worker.
The “file” here is a string stream, so the demo can print it. FileSink
is tested on its own in ac_5_1.
Shutdown
Section titled “Shutdown”Text description of the diagram
At the end of the scope in main, the LogSystem’s destructor runs. It first flushes every sink. The AsyncSink’s flush reads its accepted count as a target and waits until written plus failed reaches it, while the worker thread writes the records still queued to the inner sink; then it flushes the inner sink. Next the LogSystem’s routes are destroyed, which destroys the AsyncSink. Its destructor sets closing under the lock and wakes the worker. The worker finds the queue empty and closing set, and returns. The destructor joins the worker, flushes the inner sink once more, and then the inner sink is destroyed.
Diagram source (Mermaid)
sequenceDiagram
participant M as main
participant S as LogSystem
participant A as AsyncSink
participant W as worker thread
participant F as inner sink
M->>S: end of scope, destructor
S->>A: flush()
A->>A: target is accepted, wait for written plus failed
W->>F: write the records still queued
A->>F: flush()
S->>S: routes destroyed
S->>A: destructor
A->>A: lock, closing, unlock, wake worker
W->>W: queue empty and closing, return
A->>A: join the worker
A->>F: flush, then the inner sink is destroyedRecords still in an asynchronous sink’s queue when it is destroyed,
with no flush first, are written too: run returns only when the queue
is empty. ac_7_3 tests that case by destroying an AsyncSink
directly. No record can arrive while ~LogSystem runs: by then every
thread that logs must have stopped (INV-7), since dispatch would be
reading routes that are being destroyed.
The tests are in step-1/tests/test_step1.cpp, named after the
acceptance criteria. Most build a LogSystem with one memory sink and a
fixed clock:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Helpers shared by the tests below. Each test gets its own fresh objects,// so no test can be affected by another.
// One fixed moment, 2026-03-01 09:00:00.000 UTC, used as "now" everywhere.const Timestamp t0 = sys_days{2026y / March / 1} + 9h;
// A clock that always says t0, so every time a test checks is known.Clock fixed_clock() { return [] { return t0; };}
// A record from the logger "test" at time t0, for tests that call a sink// directly instead of going through a logger.Record make(Level level, std::string message) { return Record{level, "test", std::move(message), t0};}
// One memory sink at a given minimum level, in a log system of its own.// A test makes a Rig, logs through rig.logs, and reads what arrived in// rig.captured.struct Rig { // Members are destroyed in the reverse of their order here, so logs // (and its sink, which refers to captured) goes first. Captured captured; // declared first, so it outlives the system LogSystem logs;
explicit Rig(Level sink_min = Level::debug, Level default_level = Level::info) : logs(routes(captured, sink_min), fixed_clock(), default_level) {}
// The one route: a MemorySink adding to `into`, at level `min`. static std::vector<Route> routes(Captured& into, Level min) { std::vector<Route> r; r.push_back({std::make_unique<MemorySink>(into), min}); return r; }};
// A sink whose write waits until the test opens it. With it the test// decides when the async sink's worker is busy, so a full queue is not a// matter of timing.class GateSink final : public Sink {public: explicit GateSink(Captured& into) : into_(into) {}
// Counts that a write has started (and tells wait_until_entered), then // blocks until open() has been called. Once the gate is open it stays // open, so later writes pass straight through. void write(const Record& record) override { std::unique_lock lock(mutex_); ++entered_; changed_.notify_all(); changed_.wait(lock, [&] { return open_; }); lock.unlock(); into_.add(record); } void flush() override {}
// Notify under the lock: once the worker sees open_ it can return and // the sink can be destroyed, so the gate must not touch changed_ after // releasing the mutex (a test destroys the sink while opening it). void open() { const std::lock_guard lock(mutex_); open_ = true; changed_.notify_all(); } // Blocks the test until write has been entered at least n times, so // the test knows the worker really is stuck inside a write. void wait_until_entered(int n) { std::unique_lock lock(mutex_); changed_.wait(lock, [&] { return entered_ >= n; }); }
private: std::mutex mutex_; std::condition_variable changed_; int entered_ = 0; bool open_ = false; Captured& into_;};GateSink is the important one. Its write blocks until the test calls
open, so a test can say “the worker is now busy with record 1” and
know it is true. Without it, a test of a full queue would have to fill
the queue faster than the worker empties it, and pass or fail with the
machine’s speed: a
flaky test.
open notifies while it still holds the lock. Notifying after
unlocking is the usual advice, and AsyncSink follows it, but it is
safe only if the condition variable outlives the notify. In ac_7_3,
the sink is being destroyed on another thread while the test opens the
gate: the moment the worker sees open_, it can finish, and the
GateSink can be destroyed while open is still inside
notify_all. ThreadSanitizer reported exactly that race in an earlier
version of this test, which notified after unlocking. With the notify
under the lock, the worker cannot return from write until open has
released the mutex, and open touches nothing after that.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure// if the condition is false, and LLD_CHECK_EQ(actual, expected) does the// same for "equal", printing both values when they differ. A failed check// does not stop the test; the rest of it still runs. They come from the// site's small test header, lld_test.hpp.
// Sets up a logger at info and logs once at each level. Proves that only// records at or above the logger's level reach the sink, in order.LLD_TEST(ac_1_1_a_logger_passes_records_at_or_above_its_level) { Rig rig; // loggers start at info Logger& log = rig.logs.logger("payments"); log.debug("not kept"); log.info("kept 1"); log.warn("kept 2"); log.error("kept 3"); // The extra brackets around the vector stop the macro from reading // the commas inside the braces as separators between its arguments. LLD_CHECK(rig.captured.messages() == (std::vector<std::string>{"kept 1", "kept 2", "kept 3"}));}
// Asks for "http" twice. Proves both calls return the very same object// (same address, `&a == &b`), and that another name gives another logger.LLD_TEST(ac_1_2_the_same_name_gives_the_same_logger) { Rig rig; Logger& a = rig.logs.logger("http"); Logger& b = rig.logs.logger("http"); LLD_CHECK(&a == &b); LLD_CHECK(&a != &rig.logs.logger("payments")); LLD_CHECK(a.name() == "http");}
// Loggers start at warn here. Proves that set_level on one logger takes// effect for its next record, and leaves other loggers alone.LLD_TEST(ac_1_3_a_level_can_change_while_the_program_runs) { Rig rig(Level::debug, Level::warn); // sink takes everything; loggers start at warn Logger& log = rig.logs.logger("http"); LLD_CHECK(log.level() == Level::warn); log.info("before"); // below warn: not kept log.set_level(Level::debug); log.debug("after"); LLD_CHECK(rig.logs.logger("payments").level() == Level::warn); // only http changed LLD_CHECK(rig.captured.messages() == std::vector<std::string>{"after"});}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Compares whole lines, character for character: the padded level, the// milliseconds, and the last millisecond of a year, where a date bug// would show.LLD_TEST(ac_3_1_the_two_formats_are_exact) { Record r{Level::info, "payments", "charged order 41", t0 + 250ms}; LLD_CHECK_EQ(format_line(r), std::string("2026-03-01 09:00:00.250 INFO payments: charged order 41")); LLD_CHECK_EQ(format_short(r), std::string("INFO payments: charged order 41")); r.level = Level::error; r.time = sys_days{2026y / December / 31} + 23h + 59min + 59s + 999ms; LLD_CHECK_EQ(format_line(r), std::string("2026-12-31 23:59:59.999 ERROR payments: charged order 41"));}
// The log-injection attack: a message with a real newline that tries to// fake a second, ERROR line. Proves the formatted line has no newline in// it (find returns npos, "not found"), and checks each escape exactly.LLD_TEST(ac_3_2_a_message_cannot_start_a_line_of_its_own) { const Record r{Level::info, "auth", "user bob\nERROR auth: admin logged in", t0}; const std::string line = format_line(r); LLD_CHECK(line.find('\n') == std::string::npos); LLD_CHECK_EQ(format_short(r), std::string("INFO auth: user bob\\nERROR auth: admin logged in")); // The input is 6 characters: a, backslash, n, carriage return, tab, // and the escape character 0x1b. The output doubles the backslash // (so the n stays a plain n) and spells out the other three. LLD_CHECK_EQ(escape_control(std::string_view("a\\n\r\t\x1b", 6)), std::string("a\\\\n\\r\\t\\x1b"));}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Writes 20 records into an AsyncSink over a sink that notes which thread// wrote each one. Proves they arrive in the order written, and that every// write happened on a thread other than the test's own (the worker).LLD_TEST(ac_6_1_an_async_sink_writes_in_order_on_its_own_thread) { // A sink defined inside the test, just for it. Its own mutex guards // the two vectors, which the worker fills and the test reads. struct ThreadSink final : Sink { std::mutex m; std::vector<std::thread::id> threads; std::vector<std::string> messages; void write(const Record& r) override { const std::lock_guard lock(m); threads.push_back(std::this_thread::get_id()); messages.push_back(r.message); } void flush() override {} }; auto inner = std::make_unique<ThreadSink>(); ThreadSink& seen = *inner; // a reference kept before ownership moves away // A queue of 8 for 20 records: with wait_from debug, a full queue makes // write wait for room instead of dropping. AsyncSink async(std::move(inner), 8, Level::debug); // nothing is dropped for (int i = 0; i < 20; ++i) async.write(make(Level::info, std::to_string(i))); async.flush(); // all 20 are written once this returns
const std::lock_guard lock(seen.m); LLD_CHECK_EQ(seen.messages.size(), std::size_t{20}); for (std::size_t i = 0; i < seen.messages.size(); ++i) { LLD_CHECK_EQ(seen.messages[i], std::to_string(i)); LLD_CHECK(seen.threads[i] != std::this_thread::get_id()); }}
// A queue of 2 with the worker held inside the gate. Proves that once the// queue is full, info and warn records (below error) are dropped and// counted, that the queue never holds more than 2, and that the accepted// records are all written once the gate opens.LLD_TEST(ac_6_2_when_the_queue_is_full_lower_levels_are_dropped_and_counted) { Captured captured; auto gate_owner = std::make_unique<GateSink>(captured); GateSink& gate = *gate_owner; AsyncSink async(std::move(gate_owner), 2); // wait_from = error
async.write(make(Level::info, "r1")); gate.wait_until_entered(1); // the worker holds r1, and the queue is empty async.write(make(Level::info, "r2")); async.write(make(Level::info, "r3")); // the queue is full async.write(make(Level::info, "r4")); // dropped: info is below error async.write(make(Level::warn, "r5")); // dropped: warn is below error too AsyncStats s = async.stats(); LLD_CHECK_EQ(s.accepted, std::uint64_t{3}); LLD_CHECK_EQ(s.dropped, std::uint64_t{2});
gate.open(); async.flush(); s = async.stats(); LLD_CHECK_EQ(s.written, std::uint64_t{3}); LLD_CHECK_EQ(s.high_water, std::size_t{2}); LLD_CHECK(captured.messages() == (std::vector<std::string>{"r1", "r2", "r3"}));}
// The same full queue, but the extra record is an error. Proves it waits// for room (on its own thread, so the test can carry on and open the// gate) and is then written, last, with nothing dropped.LLD_TEST(ac_6_3_an_error_waits_for_room_instead_of_being_dropped) { Captured captured; auto gate_owner = std::make_unique<GateSink>(captured); GateSink& gate = *gate_owner; AsyncSink async(std::move(gate_owner), 2);
async.write(make(Level::info, "r1")); gate.wait_until_entered(1); async.write(make(Level::info, "r2")); async.write(make(Level::info, "r3")); // full // This write will block, so it runs on a second thread. [&] lets the // lambda use `async` by reference. std::thread writer([&] { async.write(make(Level::error, "e4")); }); // Spin, giving up the processor each time (yield), until the writer is // counted as waiting. Then the test knows e4 really is blocked. while (async.stats().waiting == 0) std::this_thread::yield(); // e4 is waiting
gate.open(); // the worker finishes r1, pops r2, and e4 gets its place writer.join(); // wait for the writer thread to finish async.flush(); const AsyncStats s = async.stats(); LLD_CHECK_EQ(s.dropped, std::uint64_t{0}); LLD_CHECK_EQ(s.high_water, std::size_t{2}); // waited; did not overfill LLD_CHECK(captured.messages() == (std::vector<std::string>{"r1", "r2", "r3", "e4"}));}ac_6_3 loops until stats().waiting is no longer 0 before opening
the gate, so it knows the error writer really is waiting, not merely
started. The high_water check is what catches a queue that lets one
extra record in.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// 500 records through an async route, then one flush. Proves flush does// not return early: all 500 are in the memory sink when it does.LLD_TEST(ac_7_1_flush_returns_after_everything_accepted_is_written) { Captured captured; std::vector<Route> routes; routes.push_back({std::make_unique<AsyncSink>(std::make_unique<MemorySink>(captured), 1000), Level::debug}); LogSystem logs(std::move(routes), fixed_clock()); Logger& log = logs.logger("app"); for (int i = 0; i < 500; ++i) log.info("line " + std::to_string(i)); logs.flush(); LLD_CHECK_EQ(captured.size(), std::size_t{500});}
// The same 500 records, but the system is simply destroyed, with no// flush call. Proves nothing accepted is lost at shutdown.LLD_TEST(ac_7_2_destroying_the_system_writes_everything_accepted) { Captured captured; // outlives the system { std::vector<Route> routes; routes.push_back({std::make_unique<AsyncSink>(std::make_unique<MemorySink>(captured), 1000), Level::debug}); LogSystem logs(std::move(routes), fixed_clock()); Logger& log = logs.logger("app"); for (int i = 0; i < 500; ++i) log.info("line " + std::to_string(i)); } // no flush call const std::vector<std::string> messages = captured.messages(); LLD_CHECK_EQ(messages.size(), std::size_t{500}); // `!messages.empty() &&` first, so back() is never called on an empty // vector (that would be undefined behaviour). LLD_CHECK(!messages.empty() && messages.back() == "line 499");}// Destroys an AsyncSink directly, with no flush first, while the worker is// stuck on r1 and r2, r3 are still queued. Proves the destructor waits for// the worker to write the queued records before it stops it.LLD_TEST(ac_7_3_destroying_an_async_sink_writes_its_queue_first) { Captured captured; auto gate_owner = std::make_unique<GateSink>(captured); GateSink& gate = *gate_owner; // valid until the async sink is destroyed auto async = std::make_unique<AsyncSink>(std::move(gate_owner), 4); async->write(make(Level::info, "r1")); gate.wait_until_entered(1); // the worker holds r1 async->write(make(Level::info, "r2")); async->write(make(Level::info, "r3")); // two still queued, no flush
// reset() destroys the AsyncSink the unique_ptr owns. Its destructor // blocks until the worker is done, so it runs on another thread while // this one opens the gate. std::thread destroyer([&async] { async.reset(); }); // waits for the worker // The pause lets the destructor mark the sink closing before the worker // goes on. The test passes without it; with it, it also catches a // worker that stops at closing with records still queued. std::this_thread::sleep_for(50ms); gate.open(); destroyer.join(); LLD_CHECK(captured.messages() == (std::vector<std::string>{"r1", "r2", "r3"}));}The route, lazy-message, and failure tests are in the route-tests,
lazy-test, and failure-test regions of the same file.
Invariants under many threads. Three tests run several threads at
once. One logs 8 × 2,000 records through a queue of 16 that never
drops and checks that each thread’s records arrive once, in order
(INV-3). One logs 4 × 5,000 through a queue of 4 that drops, and checks
accepted + dropped against what was sent and high_water ≤ 4 (INV-1,
INV-2). One writes 8 × 500 lines to a stream and checks that every line
is whole (INV-4).
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// 8 threads each log 0, 1, ..., 1999 through their own logger into one// async sink with a queue of 16 that never drops. Proves every record// arrives exactly once, and each thread's records stay in its own order// (records from different threads may mix, which is fine).LLD_TEST(inv_many_threads_each_record_once_and_in_order) { constexpr int threads = 8; constexpr int per_thread = 2000; Captured captured; { std::vector<Route> routes; // wait_from debug: nothing is dropped, so every record must arrive. routes.push_back({std::make_unique<AsyncSink>(std::make_unique<MemorySink>(captured), 16, Level::debug), Level::debug}); LogSystem logs(std::move(routes), fixed_clock()); // Declared after logs, so these threads are joined (jthread's // destructor waits for each) before logs is destroyed. std::vector<std::jthread> workers; for (int t = 0; t < threads; ++t) { // emplace_back starts a thread running the lambda. It captures // logs by reference (shared) and t by value (each thread its own). workers.emplace_back([&logs, t] { Logger& log = logs.logger("worker " + std::to_string(t)); for (int i = 0; i < per_thread; ++i) log.info(std::to_string(i)); }); } } // workers joined first, then the system writes what it accepted
const std::vector<Record> records = captured.records(); LLD_CHECK_EQ(records.size(), static_cast<std::size_t>(threads * per_thread)); // last_seen[t] is the last number seen from thread t; -1 means none // yet. Each record must be exactly one more than the last from its // thread: a gap, a repeat, or a swap fails the check. std::vector<int> last_seen(threads, -1); for (const Record& r : records) { // "worker " is 7 characters, so substr(7) is the thread's number; // stoi turns that text into an int. const int t = std::stoi(r.logger.substr(7)); const int i = std::stoi(r.message); LLD_CHECK_EQ(i, last_seen[static_cast<std::size_t>(t)] + 1); // once each, in order last_seen[static_cast<std::size_t>(t)] = i; }}
// 4 threads log 5,000 records each into a queue of only 4 that drops// below error, so some are usually dropped (how many depends on timing).// Proves no record is unaccounted for// (accepted + dropped is all 20,000), every accepted one is written, and// the queue never held more than 4.LLD_TEST(inv_accepted_plus_dropped_is_everything_written) { constexpr int threads = 4; constexpr int per_thread = 5000; Captured captured; AsyncStats s; { auto async = std::make_unique<AsyncSink>(std::make_unique<MemorySink>(captured), 4); AsyncSink& sink = *async; std::vector<Route> routes; routes.push_back({std::move(async), Level::debug}); LogSystem logs(std::move(routes), fixed_clock()); { std::vector<std::jthread> workers; for (int t = 0; t < threads; ++t) { workers.emplace_back([&logs] { Logger& log = logs.logger("w"); // all four share one logger for (int i = 0; i < per_thread; ++i) log.info("x"); }); } } // the threads are joined here, so all logging is over logs.flush(); s = sink.stats(); } LLD_CHECK_EQ(s.accepted + s.dropped, static_cast<std::uint64_t>(threads * per_thread)); LLD_CHECK_EQ(s.written, s.accepted); LLD_CHECK_EQ(captured.size(), static_cast<std::size_t>(s.accepted)); LLD_CHECK(s.high_water <= 4);}
// 8 threads write 500 lines each, straight to a StreamSink with no queue.// Proves every line comes out whole: if two writes ever mixed, some line// would not equal "INFO w: " followed by 40 letters a.LLD_TEST(inv_lines_from_many_threads_never_interleave) { std::ostringstream out; { std::vector<Route> routes; routes.push_back({std::make_unique<StreamSink>(out, format_short), Level::debug}); LogSystem logs(std::move(routes), fixed_clock()); std::vector<std::jthread> workers; for (int t = 0; t < 8; ++t) { workers.emplace_back([&logs] { Logger& log = logs.logger("w"); for (int i = 0; i < 500; ++i) log.info(std::string(40, 'a')); }); } } // Read the text back line by line; ++lines counts each one. std::istringstream in(out.str()); int lines = 0; for (std::string line; std::getline(in, line); ++lines) { LLD_CHECK_EQ(line, "INFO w: " + std::string(40, 'a')); } LLD_CHECK_EQ(lines, 8 * 500);}Did the tests check enough? The step 2 code (which contains all of
step 1) was changed in 34 small ways. The changes were written by hand;
a script applied them one at a time to a copy of the code and ran the
step 2 tests after each. The changes included: dropping records
at wait_from, not counting drops, letting the queue overfill by one,
a flush that does not wait, a shutdown that stops at closing_ with
records still queued, counting failures as written, making the route
and logger levels exclusive, letting the first failing sink stop the
rest, not counting a failing flush, building a lazy message when the
level is off, not escaping a backslash, not padding the level, and
eighteen changes to the fields, the JSON, and the rotation, and three
to the file failures: not flushing each line, not closing the file
after a failed write, and never opening it again. Three of
them first passed every test: the shutdown that stops early (the
LogSystem destructor flushes first, which hid it; ac_7_3 destroys
an AsyncSink directly), rotating when a line would fill the file
exactly (fixed by making ac_10_1’s limit exactly two lines), and
rotating an empty file (fixed by restructuring ac_10_2). Two real bugs
in the rotation retry were found by reading the code, not by mutation;
their tests came first, then their mutants. Now each of the 34 makes at
least one test fail. Two of them do it by hanging: with wait_from
dropped from < to <= or the queue allowed one extra record,
ac_6_3 waits for a writer that never waits, and the test run was
stopped by a timeout. A hang is a failing test, but a slow way to learn
it. A third hang was the test’s own fault: with lines not flushed,
app.log in ac_10_5 was still the link to /dev/full, and reading
/dev/full never ends. The test now checks for the link before it
reads the file.
Mutation only finds the bugs someone thought to write. One plausible
bug is argued against here, not tested: a flush that waits for the
queue to be empty, instead of for its own target, would wait forever
while other threads keep logging. No test logs from another thread
during a flush, so the suite would not notice.
Run them with:
cd examplescmake --preset gcc-debug && cmake --build --preset gcc-debugctest --preset gcc-debug -R cs_loggingThe tests carry the concurrency label, so the tsan preset runs them
under ThreadSanitizer as well.
Concurrency and shutdown
Section titled “Concurrency and shutdown”Every part of the library is used from several threads. What each part does about it:
- A logger’s level is a
std::atomic<Level>read withmemory_order_relaxed. It is a single value that publishes nothing else, so no stronger ordering is needed; a thread that reads the old level for a moment afterset_levellogs one more or one fewer line. See Thread safety. - The logger map is guarded by a mutex, and only
logger()uses it. Components look a logger up once and keep the reference. - The routes never change after construction, so they are read without a lock.
- Each sink guards its own state.
StreamSinkandFileSinkformat before they lock and write one string under the lock. AsyncSinkhas one mutex and two condition variables:has_work_for the worker, andprogress_for writers waiting for room and forflush. Keeping them apart means a new record wakes only the worker.writenotifies after unlocking, so the woken worker does not wake only to block on the mutex; that is safe here because the sink is alive for the whole call.- Times can be slightly out of order across threads. The time is
read in
submit, before the record reaches a queue. Two threads can read 09:00:00.001 and 09:00:00.002 and reach the queue in the other order. Within one thread the order is always right. - A sink must never log through its own system. Suppose a
FileSinklogged “disk is slow” aterrorthrough the same system. It runs on theAsyncSink’s worker; the error goes todispatch, then to the sameAsyncSink::write; the queue is full, so the error waits for room; and the only thread that makes room is the one waiting. That is a deadlock, which is why theSinkcontract forbids it. - Destruction order is declaration order, reversed. In the demo,
file_textis declared before the system andPaymentServiceafter it, so the service goes first, then the system (which flushes and drains), and the string the file wrote into is still there. See Async, cancellation, and shutdown. ~AsyncSinkassumes no other thread is still writing. The log system destroys its sinks in its own destructor, so that holds only if every thread that logs has stopped before the system is destroyed. Arranging that ismain’s job (INV-7): join the worker threads, then let the system go.
What was checked. Both steps’ tests run under the tsan preset
(Clang 14 with ThreadSanitizer), including the three many-thread tests,
and were then run ten times in a row. ThreadSanitizer reported no
race in the library. It did find the race in the test’s GateSink
described in Tests. ThreadSanitizer reports races that happen
in the runs it watches; a clean run is evidence, not a proof.
The clock. Logger::log calls the clock on the caller’s thread,
with no lock, so the clock must be safe to call from several threads at
once. system_now is. The stepping clocks in the demo and in ac_2_2
change a variable with no lock; they are safe only because one thread
logs there, so do not copy them into a test with many threads.
Persistence. The file is the only thing kept, and nothing is
fsynced. A crash loses whatever is in the queue and whatever the
operating system has not yet written.
When the requirements change
Section titled “When the requirements change”Two weeks in, support asks for two things:
“We want every line for order 42. Searching the text for
42also findscents=4200andtook 42 ms. And last night the log disk filled up and the service stopped logging.”
This is an ordinary change: a new kind of data in a record, two output formats, and a new sink. New requirements:
- FR-8 Fields. A record can carry fields, each a key and a value that is text, an integer, or true/false, in the order given.
- FR-9 Searchable formats. The text formats add fields as
key=value, quoting a value when it has to be. A new format writes one JSON object per line, for programs. - FR-10 A rotating file. A file sink that starts a new file before the current one passes a size, and keeps at most a given number of old files.
What moved
Section titled “What moved”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Step 2: a value a program can search for, kept apart from the message.// A std::variant holds exactly one of the listed types at a time: here a// piece of text, a 64-bit integer, or true/false. It remembers which one// it holds, so a formatter can write 42 as a number and "42" as text.using Value = std::variant<std::string, std::int64_t, bool>;
// One key and its value, such as order=42. A caller usually writes it as// a brace pair, {"order", 42}, and the matching constructor below is// chosen from the type of the second part.struct Field { // One constructor per kind of value the caller may pass. Without the // const char* one, Field("card", "visa") would pick bool: a pointer // converts to bool by a standard conversion, which beats the // user-defined conversion to std::string. The int one exists because // 42 is an int, and int converts equally well to std::int64_t and to // bool, so without it {"order", 42} would be ambiguous and not compile. // Each constructor moves the name into `key` instead of copying it. Field(std::string name, std::string text) : key(std::move(name)), value(std::move(text)) {} Field(std::string name, const char* text) : key(std::move(name)), value(std::string(text)) {} Field(std::string name, std::int64_t number) : key(std::move(name)), value(number) {} Field(std::string name, int number) : key(std::move(name)), value(std::int64_t{number}) {} Field(std::string name, bool flag) : key(std::move(name)), value(flag) {}
std::string key; Value value;
// `= default` asks the compiler to write ==: two fields are equal when // their keys and values are equal. The tests use it. bool operator==(const Field&) const = default;};
// One log statement, complete: a sink needs nothing else to write it.struct Record { Level level = Level::info; std::string logger; // the name of the logger that made it std::string message; Timestamp time{}; // No `{}` here on purpose: with the project's warnings, any place that // brace-initialises a Record without saying its fields fails to build. std::vector<Field> fields; // step 2; in the order the caller gave them};Value is a std::variant of the three kinds the team asked for.
Field needs five constructors, and each is there for a reason:
- Without
const char*,Field("card", "visa")holds abool. A string literal converts toboolby a standard conversion, which beats the user-defined conversion tostd::string. With this project’s flags (-Wall -Wextra -Wpedantic) it compiles with no warning on GCC 11 or Clang 14, andcard=trueis written to the log. Clang’s-Wconversiondoes catch it (“implicit conversion turns string literal into bool”, from-Wstring-conversion); GCC 11 stays silent even then.ac_9_1checks that the value is a string. - Without
int,{"order", 42}would have to choose betweenstd::int64_tandbool, and the call is ambiguous. - What is still ambiguous:
Field("n", std::size_t{3})andField("n", 3LL)do not compile, because neither converts to one overload better than the others. The caller writesstatic_cast<std::int64_t>(n). That is a compile error, not a wrong value, so it was left.
Record::fields has no default member initializer, on purpose. With
-Wextra -Werror, every brace-initialization of a Record that leaves
out the new member is a compile error
(-Wmissing-field-initializers). Building the unchanged step 1 code
against the step 2 record.hpp stopped at exactly four places:
Logger::submit, and three records in the tests. Each one is a place
that has to decide what its fields are. With fields{}, neither
compiler warns.
The formatters are the warning that did not happen. Step 1’s
format_line and format_short compile unchanged against the step 2
record and simply leave the fields out. The compiler cannot know that a
formatter ought to read every member; only a test can, and ac_9_3
does.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Step 2: a message with fields, as in// log.warn("card declined", {{"order", 42}, {"retry", false}});// The brace list builds the vector in the caller, before the level is// checked. It is taken by value and moved on to log, so the fields are// not copied again. A call with two arguments goes here, because the// step 1 shorthands take exactly one.void debug(std::string_view message, std::vector<Field> fields) noexcept { log(Level::debug, message, std::move(fields));}void info(std::string_view message, std::vector<Field> fields) noexcept { log(Level::info, message, std::move(fields));}void warn(std::string_view message, std::vector<Field> fields) noexcept { log(Level::warn, message, std::move(fields));}void error(std::string_view message, std::vector<Field> fields) noexcept { log(Level::error, message, std::move(fields));}log takes std::vector<Field> fields = {}, so every step 1 call still
compiles. The four new overloads let a component write
log_.warn("card declined", {{"order", order}, {"retry", false}}); the
step 1 templates take one argument, so a call with fields goes to these. The
vector is built by the caller, before the level is checked: a disabled
debug line with fields still allocates them, and if that allocation
throws, it throws in the caller’s expression, outside the noexcept
function. A caller on a hot path can write
if (log.enabled(Level::debug)) first.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The fields as text for format_line and format_short: " key=value" for// each, in order, or "" when there are none. Two helpers (in the same// file) keep a field from forging another: text_key turns any character// other than a letter, digit, '_', '.', or '-' into '_' (and an empty key// into "_"), and text_value writes a number or true/false as it is, and// quotes text that is empty or has a space, '=', '"', a backslash, or a// control character. So {"user", "role=admin"} becomes user="role=admin".std::string format_fields(const std::vector<Field>& fields) { std::string out; for (const Field& field : fields) { // ' ' + text_key(...) works because the right side is a std::string. out += ' ' + text_key(field.key) + '=' + text_value(field.value); } return out;}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The text as a JSON string: wrapped in double quotes, with the// characters JSON does not allow raw inside a string escaped. The idea is// the same as escape_control, with JSON's spelling of each escape.std::string json_string(std::string_view text) { std::string out = "\""; // the opening quote for (const char c : text) { const auto byte = static_cast<unsigned char>(c); // 0 to 255, as in escape_control if (c == '"') { // A quote inside the text would end the JSON string early, so it // is written as backslash and quote. out += "\\\""; } else if (c == '\\') { out += "\\\\"; } else if (c == '\n') { out += "\\n"; } else if (c == '\r') { out += "\\r"; } else if (c == '\t') { out += "\\t"; } else if (byte < 0x20) { // JSON's form for other control characters is backslash, u, and // four hex digits: 0x1b becomes the six characters "\u001b". char hex[8]; std::snprintf(hex, sizeof hex, "\\u%04x", static_cast<unsigned>(byte)); out += hex; } else { out += c; } } return out + '"'; // the closing quote}
// One record as one JSON object, for programs to read:// {"time":"...Z","level":"WARN","logger":"...","message":"...","fields":{...}}// Every piece of text goes through json_string, so no message or field// can break the object. Numbers and true/false are written bare.std::string format_json(const Record& record) { std::string time = format_time(record.time); // "2026-03-01 09:00:00.250" // The common machine-readable time form, ISO 8601, has a T between // date and time and Z at the end for UTC: "2026-03-01T09:00:00.250Z". // format_time always has exactly one space, so find never fails here. time[time.find(' ')] = 'T'; // In C++ source, \" is a quote character inside a string literal. std::string out = "{\"time\":\"" + time + "Z\",\"level\":" + json_string(to_string(record.level)) + ",\"logger\":" + json_string(record.logger) + ",\"message\":" + json_string(record.message) + ",\"fields\":{"; // The fields object: "key":value pairs, with a comma before every pair // except the first (JSON does not allow a trailing comma). json_value // writes text through json_string, and numbers and booleans bare. for (std::size_t i = 0; i < record.fields.size(); ++i) { if (i > 0) out += ','; out += json_string(record.fields[i].key) + ':' + json_value(record.fields[i].value); } return out + "}}"; // close the fields object, then the record object}The text format keeps a key to letters, digits, _, ., and -, and
quotes a value with a space, =, a quote, a backslash, or a control
character. So {"user", "role=admin"} is written user="role=admin",
and no value can add a field of its own. The JSON format puts the fields
in an object of their own, so a field called message cannot replace
the message. Both read the value with std::visit and an overload set
whose lambdas each take exactly one type
(const std::same_as<std::int64_t> auto&, and so on). That is what
makes the compiler check the formatters: a lambda written
[](std::int64_t n) would also accept any type that converts to
std::int64_t, so a new kind of value could quietly take the wrong
case. A const char* added to Value would go to a [](bool) lambda,
the same trap as in Field. With exact types, adding a double or a
const char* to Value makes both std::visit calls fail to compile
(checked on both compilers), and the errors point at the two
formatters that need a new case.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Step 2. Like FileSink, but a file never grows past max_bytes unless one// line is longer than that. Before a line that would not fit, the files// move up: app.log.(keep-1) becomes app.log.keep (the old app.log.keep is// deleted), ..., app.log becomes app.log.1, and a new app.log is started.// At most keep old files remain. Lines are flushed one by one, as in// FileSink. Throws std::invalid_argument if max_bytes or keep is 0, and// std::runtime_error as FileSink does. A write or a rotation that fails// throws from write and leaves the file closed: that record is lost, and// the next write rotates, so it starts a clean file.class RotatingFileSink final : public Sink {public: // Opens path for appending and counts the bytes already in it, so a // restarted program keeps to the same limit. std::uintmax_t is the // largest unsigned integer type, the type std::filesystem uses for // file sizes. RotatingFileSink(std::filesystem::path path, Formatter format, std::uintmax_t max_bytes, int keep); void write(const Record& record) override; void flush() override;
private: std::filesystem::path numbered(int n) const; // app.log.n void rotate(); // called with mutex_ held
std::mutex mutex_; // guards out_ and size_: one write or rotation at a time const std::filesystem::path path_; Formatter format_; const std::uintmax_t max_bytes_; const int keep_; std::ofstream out_; // the current file; closed after a failure std::uintmax_t size_ = 0; // bytes in the current file};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Writes one whole line, rotating first if needed. Throws (and the record// is lost) if the rotation or the write fails; the log system counts it.void RotatingFileSink::write(const Record& record) { const std::string line = format_(record) + '\n'; // formatted before the lock const std::lock_guard lock(mutex_); // held through the rotation and the write // A closed file means the last write or rotation failed. Rotating // again starts a clean file, so a line cut short by a full disk ends // its file instead of running into the next line. // Otherwise rotate only if the file already holds something and this // line would take it past the limit. `size_ > 0` means an empty file // is never rotated: a line longer than the limit gets a file to itself. if (!out_.is_open() || (size_ > 0 && size_ + line.size() > max_bytes_)) rotate(); write_line(out_, line); // throws, and closes the file, if the line cannot be written size_ += line.size(); // reached only if the write worked}
// Moves every file up one number and starts an empty app.log. Throws// std::filesystem::filesystem_error if a rename (or a check) fails, or// std::runtime_error if the new file cannot be opened; either way the// file is left closed, so the next write calls rotate again.
void RotatingFileSink::rotate() { namespace fs = std::filesystem; out_.close(); // rename replaces the file it moves onto, so the oldest simply goes. // If a rename throws, size_ is unchanged and the next write tries the // whole rotation again. If app.log is not there (an attempt moved it // and then could not open the new one, or someone deleted it), there // is nothing to move: just start the new file. if (fs::exists(path_)) { // Oldest first, counting down: with keep 3, .2 moves onto .3 (the // old .3 is gone), then .1 onto .2. Counting up instead would move // .1 onto .2 first and destroy .2 before it had moved. for (int n = keep_ - 1; n >= 1; --n) { if (fs::exists(numbered(n))) fs::rename(numbered(n), numbered(n + 1)); } fs::rename(path_, numbered(1)); // the current file becomes .1 } // trunc: open empty, removing anything already there. out_.open(path_, std::ios::trunc); if (!out_.is_open()) throw std::runtime_error("cannot open log file " + path_.string()); size_ = 0;}How this code works: RotatingFileSink::write and rotate, traced
write decides, rotate moves files. Under the lock, write asks one
question: “must the current file be closed off before this line?” The
answer is yes in two cases:
- the file is closed, which only happens after a failed write or a failed rotation; or
- the file already holds something (
size_ > 0) and the line would take it past the limit (size_ + line.size() > max_bytes_). A line that exactly fills the file is still written to it.
Then it writes the line and adds its length to size_. If the write
throws, the size_ += line is skipped, and the file is already closed
by write_line.
rotate closes the file and, if app.log exists, shifts the numbered
files up by one, counting down from keep_ - 1 so no file is
overwritten before it has moved. A rename onto an existing file
replaces it, so the file at number keep_ simply disappears. Then
app.log becomes app.log.1, and an empty app.log is opened.
A trace of the step 2 demo. Each line is 30 bytes, max_bytes_ is
60, and keep_ is 2, so the only rename in the loop is .1 to .2.
| Line | size_ before |
Rotate? | Files after the write |
|---|---|---|---|
| 1 | 0 | no: the file is empty | app.log = 1 |
| 2 | 30 | no: 30 + 30 = 60, not > 60 | app.log = 1, 2 |
| 3 | 60 | yes: 90 > 60 | app.log = 3; .1 = 1, 2 |
| 4 | 30 | no | app.log = 3, 4; .1 = 1, 2 |
| 5 | 60 | yes | app.log = 5; .1 = 3, 4; .2 = 1, 2 |
| 6 | 30 | no | app.log = 5, 6; .1 = 3, 4; .2 = 1, 2 |
| 7 | 60 | yes: .2 (1, 2) is replaced |
app.log = 7; .1 = 5, 6; .2 = 3, 4 |
That is the output: one line in app.log, two each in app.log.1 and
app.log.2, no app.log.3, and lines 1 and 2 gone.
After a failure. In test ac_10_4, the limit is 50 and app.log
holds two 18-byte lines (36 bytes). The third line does not fit, and the
rotation fails because app.log cannot be renamed. rotate had already
closed the file, so it stays closed, and size_ is still 36. The next
line is only 13 bytes and would fit beside the 36, but write sees the
closed file and calls rotate first, so the rotation that failed is
finished before anything else is written.
RotatingFileSink is a new sink and nothing else changes for it: the
log system, the routes, and AsyncSink see one more Sink. Wrapped in
an AsyncSink, its rotation (several renames on a network disk) runs
on the worker thread, never on a thread that logs.
Text description of the diagram
When a line would take the current file past its limit, the sink rotates before writing it. With keep set to 2, app.log.1 is renamed to app.log.2, which replaces the old app.log.2, so the oldest file is gone. Then app.log is renamed to app.log.1. A new, empty app.log is opened, and the line is written to it.
Diagram source (Mermaid)
flowchart LR
next[a line that does not fit] --> rot[rotate]
rot --> two[app.log.1 is renamed to app.log.2, replacing the old app.log.2]
two --> one[app.log is renamed to app.log.1]
one --> fresh[a new empty app.log is opened]
fresh --> write[the line is written to it]The rotation rules, and the reason for each:
- Rotate before a line that does not fit, never in the middle of a line, so every file holds whole lines.
- Never rotate an empty file. A line longer than the limit goes into
an empty file and gets that file to itself (AC-10.2). Without the
size_ > 0check, it would rotate an empty file away first. - Count what is already there. When the program starts again, the constructor reads the file’s size, so the limit holds across restarts (AC-10.3).
- A failed rotation is retried, not hidden. If a rename throws, the
write throws (the log system counts it), that record is lost, and the
file is left closed. The next write sees the closed file and tries the
whole rotation again, even if its line would have fitted (AC-10.4).
An earlier version only retried when the next line did not fit, so a
short line after a failure was written to a closed stream and lost;
ac_10_4now writes a short line after the failure. - A failed write starts a clean file. A write to a full disk can leave part of a line in the file. The sink then closes the file, and the next write sees the closed file and rotates, so the cut line ends its file instead of running into the next line (AC-10.5).
- No current file, nothing to move. If
app.logis missing (an attempt moved it and then could not create the new one, or someone deleted it), rotating just starts a new file. An earlier version renamed the old files anyway and then failed on the missingapp.log, on every write, until the program was restarted.
What did not move: AsyncSink (both files are byte-for-byte the
same in the two steps), dispatch, logger(), the routes, the Sink
interface, and every step 1 test, which runs again in step 2 with {}
added to three records.
Step 2 tests
Section titled “Step 2 tests”All step 1 tests run again against step 2. The new ones:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST, LLD_CHECK, LLD_CHECK_EQ, and LLD_CHECK_THROWS come from the// site's test header, lld_test.hpp, as in step 1. Rig (a log system with// one memory sink, rig.captured) and make (a record from logger "test")// are the step 1 fixtures.
// Logs one record with an int, a string literal, and a bool. Proves the// three fields arrive in order, and that each value holds the right kind:// std::holds_alternative<T>(v) is true if the variant v holds a T now.// The middle check is the Field("card", "visa") trap: it must be text.LLD_TEST(ac_9_1_fields_travel_with_the_record_and_keep_their_kind) { Rig rig; rig.logs.logger("payments").warn("card declined", {{"order", 42}, {"card", "visa"}, {"retry", false}}); const std::vector<Record> records = rig.captured.records(); LLD_CHECK_EQ(records.size(), std::size_t{1}); // A failed check does not stop the test, so return before indexing a // vector that is too short. if (records.size() != 1) return; LLD_CHECK(records[0].fields == (std::vector<Field>{{"order", 42}, {"card", "visa"}, {"retry", false}})); if (records[0].fields.size() != 3) return;
LLD_CHECK(std::holds_alternative<std::int64_t>(records[0].fields[0].value)); LLD_CHECK(std::holds_alternative<std::string>(records[0].fields[1].value)); // not bool LLD_CHECK(std::holds_alternative<bool>(records[0].fields[2].value));}
// The record goes through an AsyncSink's queue (a copy, on another// thread). Proves the fields are copied with it, not lost.LLD_TEST(ac_9_2_an_async_sink_carries_the_fields) { Captured captured; { std::vector<Route> routes; routes.push_back({std::make_unique<AsyncSink>(std::make_unique<MemorySink>(captured), 4), Level::debug}); LogSystem logs(std::move(routes), fixed_clock()); logs.logger("app").info("saved", {{"bytes", 512}}); } // destroying the system writes the queued record first const std::vector<Record> records = captured.records(); LLD_CHECK_EQ(records.size(), std::size_t{1}); if (records.size() != 1) return; LLD_CHECK(records[0].fields == (std::vector<Field>{{"bytes", 512}}));}
// Exact text lines with fields, then the tricky keys and values. R"(...)"// is a raw string literal: everything between R"( and )" is taken as it// is, so the quotes and backslashes in the expected text need no escapes.LLD_TEST(ac_9_3_text_lines_show_fields_as_key_value) { const Record r{Level::warn, "payments", "card declined", t0, {{"order", 42}, {"card", "visa"}, {"retry", false}, {"note", "two words"}}}; LLD_CHECK_EQ(format_short(r), std::string(R"(WARN payments: card declined order=42 card=visa retry=false note="two words")")); LLD_CHECK_EQ(format_line(r), std::string(R"(2026-03-01 09:00:00.000 WARN payments: card declined order=42 card=visa retry=false note="two words")"));
// A key or a value cannot add a field of its own, or end the line. // The space and '=' in a key become '_'. A value with '=' is quoted. // Quotes in a value are escaped and its newline becomes backslash, n. // An empty key becomes "_", an empty value "", and -5 stays a number. LLD_CHECK_EQ(format_fields({{"user id=7", "bob"}}), std::string(" user_id_7=bob")); LLD_CHECK_EQ(format_fields({{"user", "role=admin"}}), std::string(R"( user="role=admin")")); LLD_CHECK_EQ(format_fields({{"note", "say \"hi\"\n"}}), std::string(R"( note="say \"hi\"\n")")); LLD_CHECK_EQ(format_fields({{"", ""}, {"delta", -5}}), std::string(R"( _="" delta=-5)"));}
// The same record as text and as JSON. In text, "order=99" in the message// and a field named "message" look like real fields; in JSON, the message// and the fields object are separate, so a program reads them correctly.// Then json_string's escapes, and a record with no fields ("fields":{}).LLD_TEST(ac_9_4_json_lines_are_exact_and_cannot_be_confused) { // In text, the message can look like a field: a person can tell, a // program cannot. const Record r{Level::info, "payments", "charged order=99", t0 + 250ms, {{"order", 41}, {"message", "a field, not the message"}}}; LLD_CHECK_EQ(format_short(r), std::string(R"(INFO payments: charged order=99 order=41 message="a field, not the message")")); LLD_CHECK_EQ(format_json(r), std::string(R"({"time":"2026-03-01T09:00:00.250Z","level":"INFO","logger":"payments","message":"charged order=99","fields":{"order":41,"message":"a field, not the message"}})"));
LLD_CHECK_EQ(json_string("say \"hi\"\n\\ \x01"), std::string(R"("say \"hi\"\n\\ \u0001")")); const Record plain{Level::debug, "app", "", t0, {}}; LLD_CHECK_EQ(format_json(plain), std::string(R"({"time":"2026-03-01T09:00:00.000Z","level":"DEBUG","logger":"app","message":"","fields":{}})"));}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Two helpers from this file: ScratchDir makes a new, empty temporary// directory and its destructor deletes it with everything inside, so// each test starts clean and leaves nothing behind. numbered_line(n)// makes the record "line n" from logger "test".
// "INFO test: line 1\n" is 18 bytes, so a 36-byte file holds exactly two.// Seven lines with keep 2: line 3 starts a new file, so do 5 and 7, and// the oldest file falls off the end. The limit is exactly two lines, so a// sink that rotated when a line would only fill the file would fail here.LLD_TEST(ac_10_1_a_rotating_sink_keeps_at_most_keep_old_files) { ScratchDir dir; const std::filesystem::path log = dir.path / "app.log"; { RotatingFileSink sink(log, format_short, 36, 2); for (int n = 1; n <= 7; ++n) sink.write(numbered_line(n)); } LLD_CHECK(read_lines(log) == std::vector<std::string>{"INFO test: line 7"}); LLD_CHECK(read_lines(dir.path / "app.log.1") == (std::vector<std::string>{"INFO test: line 5", "INFO test: line 6"})); LLD_CHECK(read_lines(dir.path / "app.log.2") == (std::vector<std::string>{"INFO test: line 3", "INFO test: line 4"})); LLD_CHECK(!std::filesystem::exists(dir.path / "app.log.3")); // lines 1 and 2 are gone}
// A 42-byte line with a 20-byte limit. Proves it is written to the empty// file (not refused, and the empty file is not rotated away first), and// that the next line, which does not fit after it, starts a new file.LLD_TEST(ac_10_2_a_line_longer_than_the_limit_gets_a_file_of_its_own) { ScratchDir dir; const std::filesystem::path log = dir.path / "app.log"; const std::string longer(30, 'z'); { RotatingFileSink sink(log, format_short, 20, 2); sink.write(make(Level::info, longer)); // 42 bytes, into the empty file sink.write(make(Level::info, "short")); // does not fit after it } LLD_CHECK(read_lines(log) == std::vector<std::string>{"INFO test: short"}); LLD_CHECK(read_lines(dir.path / "app.log.1") == std::vector<std::string>{"INFO test: " + longer}); LLD_CHECK(!std::filesystem::exists(dir.path / "app.log.2")); // an empty file is not rotated}
// Two lines, then a new sink on the same file, as after a restart. Proves// the new sink starts from the 36 bytes already there: an 18-byte line// would fit in an empty 40-byte file, but not after them, so it rotates.LLD_TEST(ac_10_3_a_reopened_sink_counts_what_the_file_already_holds) { ScratchDir dir; const std::filesystem::path log = dir.path / "app.log"; { RotatingFileSink sink(log, format_short, 40, 1); sink.write(numbered_line(1)); sink.write(numbered_line(2)); } { RotatingFileSink sink(log, format_short, 40, 1); // the file has 36 bytes sink.write(numbered_line(3)); } LLD_CHECK(read_lines(log) == std::vector<std::string>{"INFO test: line 3"}); LLD_CHECK(read_lines(dir.path / "app.log.1") == (std::vector<std::string>{"INFO test: line 1", "INFO test: line 2"}));}
// Makes a rotation fail, then removes the cause. Proves the failure is// thrown (so the log system can count it), and that the next write, even// a short one that would fit, finishes the rotation before it writes.LLD_TEST(ac_10_4_a_failed_rotation_is_reported_and_tried_again) { ScratchDir dir; const std::filesystem::path log = dir.path / "app.log"; // A directory that is not empty, where app.log.1 should go: renaming a // file onto it fails, so the rotation throws. std::filesystem::create_directories(dir.path / "app.log.1" / "in_the_way"); RotatingFileSink sink(log, format_short, 50, 1); sink.write(numbered_line(1)); sink.write(numbered_line(2)); // 36 bytes // LLD_CHECK_THROWS(expression, type) fails unless the expression throws // that type (or one derived from it): std::filesystem::filesystem_error // is a kind of std::runtime_error. LLD_CHECK_THROWS(sink.write(numbered_line(3)), std::runtime_error); // app.log cannot move std::filesystem::remove_all(dir.path / "app.log.1"); // 13 bytes would fit beside the 36, but the failed rotation is finished first. sink.write(make(Level::info, "x")); sink.write(numbered_line(4)); sink.flush(); LLD_CHECK(read_lines(log) == (std::vector<std::string>{"INFO test: x", "INFO test: line 4"})); LLD_CHECK(read_lines(dir.path / "app.log.1") == (std::vector<std::string>{"INFO test: line 1", "INFO test: line 2"}));}
// app.log is a link to /dev/full, so every write to it fails like a full// disk. Proves the failed write throws, and that the next write rotates// the bad file away (the link becomes app.log.1) and writes to a new one.LLD_TEST(ac_10_5_after_a_failed_write_the_next_one_starts_a_clean_file) { if (!std::filesystem::exists("/dev/full")) return; // as in ac_8_2 ScratchDir dir; const std::filesystem::path log = dir.path / "app.log"; // A symbolic link: an entry that points at another path, /dev/full. std::filesystem::create_symlink("/dev/full", log); RotatingFileSink sink(log, format_short, 1000, 2); LLD_CHECK_THROWS(sink.write(numbered_line(1)), std::runtime_error); sink.write(numbered_line(2)); // rotates: the full "file" moves to app.log.1 LLD_CHECK(std::filesystem::is_symlink(dir.path / "app.log.1")); // Reading /dev/full never ends, so read app.log only once it is a file. LLD_CHECK(!std::filesystem::is_symlink(log)); if (!std::filesystem::is_symlink(log)) LLD_CHECK(read_lines(log) == std::vector<std::string>{"INFO test: line 2"});}
// app.log is deleted behind the sink's back, then a line needs a rotation.// Proves the rotation does not fail on the missing file: it simply starts// a new app.log, and no app.log.1 appears.LLD_TEST(a_rotation_with_no_current_file_starts_a_new_one) { ScratchDir dir; const std::filesystem::path log = dir.path / "app.log"; RotatingFileSink sink(log, format_short, 36, 2); sink.write(numbered_line(1)); sink.write(numbered_line(2)); std::filesystem::remove(log); // gone, as after a rotation that could not finish sink.write(numbered_line(3)); // nothing to move: a new app.log sink.flush(); LLD_CHECK(read_lines(log) == std::vector<std::string>{"INFO test: line 3"}); LLD_CHECK(!std::filesystem::exists(dir.path / "app.log.1"));}The rotation tests write real files into a fresh temporary directory
that the test removes at the end. ac_10_4 makes a rotation fail by
putting a directory that is not empty where app.log.1 would go, so the
rename cannot replace it. ac_10_5 points app.log at /dev/full, a
Linux device on which every write fails as if the disk were full, so the
first line throws and the second must rotate. The step 1 test ac_8_2
does the same to a FileSink, then removes the link and checks that the
next line is written. Both tests are skipped where /dev/full does not
exist.
AC for the change.
- AC-9.1 Fields reach the sink with their kind: an integer stays an
integer,
"visa"stays text. - AC-9.2 An asynchronous sink carries the fields.
- AC-9.3 The text formats show fields as
key=value, exactly; keys are cleaned and values quoted so that no field can add another. - AC-9.4 JSON lines are exact, and a field cannot be mistaken for the message.
- AC-10.1 A rotating sink keeps at most
keepold files, each holding whole lines. - AC-10.2 A line longer than the limit gets a file of its own, and an empty file is never rotated.
- AC-10.3 A sink opened again counts what the file already holds.
- AC-10.4 A failed rotation throws and is tried again on the next write.
- AC-10.5 After a failed write, the next write rotates and starts a clean file.
The step 2 demo
Section titled “The step 2 demo”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The step 1 service, changed in two lines: the order and the amount are// now fields, not digits inside the message, so a program can search for// order 42 exactly.class PaymentService {public: explicit PaymentService(Logger& log) : log_(log) {}
bool charge(int order, int cents) { if (cents > 50'000) { // Each {key, value} pair becomes a Field; the outer braces make // the std::vector<Field>. order and cents are ints and false is a // bool, so each value keeps its kind. log_.warn("card declined", {{"order", order}, {"cents", cents}, {"retry", false}}); return false; } log_.info("charged", {{"order", order}, {"cents", cents}}); return true; }
private: Logger& log_; // not owned};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
int main() { std::ostringstream file_text; // outlives the system that writes to it
// As in step 1: a stepping clock, safe only because one thread logs. Timestamp next = sys_days{2026y / March / 1} + 9h; Clock clock = [&next] { const Timestamp now = next; next += 250ms; return now; };
{ // The same two routes as step 1. Only the file's formatter changed: // format_json instead of format_line. Nothing else knows. std::vector<Route> routes; routes.push_back({std::make_unique<StreamSink>(std::cout, format_short), Level::warn}); routes.push_back({std::make_unique<AsyncSink>( std::make_unique<StreamSink>(file_text, format_json), 64), Level::debug}); LogSystem logs(std::move(routes), clock);
PaymentService payments(logs.logger("payments")); std::cout << "-- console: warnings and above, fields as key=value\n"; payments.charge(41, 1'999); payments.charge(42, 80'000); // A forged line in the message, and a value with spaces and quotes: // the text format quotes it, and JSON escapes it. logs.logger("payments").error("refund failed\nINFO payments: refund ok", {{"order", 40}, {"reason", "bank said \"no\""}}); logs.flush(); std::cout << "-- log failures: " << logs.failures() << '\n'; }
std::cout << "-- the file: JSON lines\n" << file_text.str(); show_rotation();}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Writes 7 lines to a rotating sink with room for two lines a file and// keep 2, then reports how many lines each file holds.void show_rotation() { namespace fs = std::filesystem; // a short local name for the namespace // A new directory in the system's temporary folder, with a random // number in its name so two runs at once do not share it. `/` on paths // joins them with the right separator. const fs::path dir = fs::temp_directory_path() / ("lld_cs04_demo_" + std::to_string(std::random_device{}())); fs::create_directory(dir); { // Each line is 30 bytes, so a 60-byte file holds two. // ("INFO jobs: finished job job=1" is 29 characters, plus the newline.) RotatingFileSink sink(dir / "app.log", format_short, 60, 2); for (int n = 1; n <= 7; ++n) { // Written straight to the sink, with no log system: level, logger // name, message, time ({} is 1970, and the short format leaves it // out), and one field, job=n. sink.write(Record{Level::info, "jobs", "finished job", {}, {{"job", n}}}); } } // the sink, and its open file, are closed here, before the counting std::cout << "-- rotating sink, 7 records, 60 bytes a file, keep 2\n"; for (const char* name : {"app.log", "app.log.1", "app.log.2", "app.log.3"}) { if (fs::exists(dir / name)) { std::cout << name << ": " << count_lines(dir / name) << " line(s)\n"; } else { std::cout << name << ": none\n"; } } // Delete the directory and everything in it. Passing an error_code // picks the overload that reports failure there instead of throwing; // a demo has nothing useful to do if the cleanup fails. std::error_code ignored; fs::remove_all(dir, ignored);}-- console: warnings and above, fields as key=valueWARN payments: card declined order=42 cents=80000 retry=falseERROR payments: refund failed\nINFO payments: refund ok order=40 reason="bank said \"no\""-- log failures: 0-- the file: JSON lines{"time":"2026-03-01T09:00:00.000Z","level":"INFO","logger":"payments","message":"charged","fields":{"order":41,"cents":1999}}{"time":"2026-03-01T09:00:00.250Z","level":"WARN","logger":"payments","message":"card declined","fields":{"order":42,"cents":80000,"retry":false}}{"time":"2026-03-01T09:00:00.500Z","level":"ERROR","logger":"payments","message":"refund failed\nINFO payments: refund ok","fields":{"order":40,"reason":"bank said \"no\""}}-- rotating sink, 7 records, 60 bytes a file, keep 2app.log: 1 line(s)app.log.1: 2 line(s)app.log.2: 2 line(s)app.log.3: noneHow to read it:
- The console has the declined card with its fields as
key=value(AC-9.3), and the refund error with its forged line still one line. Thereasonvalue has spaces and quotes, so it is quoted, with the inner quotes escaped. - The file is JSON lines. Order 41 is there (the file takes
everything), the fields are in their own object, and
"no"and the newline are escaped JSON (AC-9.4). A program can now ask forfields.order == 42and get one line. - The rotating sink got seven 30-byte lines with a 60-byte limit and
keep2.app.loghas the last line,app.log.1andapp.log.2two each, and the first two lines are gone with noapp.log.3(AC-10.1).
Presenting it in an interview
Section titled “Presenting it in an interview”A plan for 45 minutes, using the time boxes from The design workflow:
| Time | What to do | What to say |
|---|---|---|
| About 5 min | Ask who logs, where lines go, what a line shows, how slow the disk is, what may be lost, and what happens at shutdown. Write FR-1 … FR-7. | “If the disk stalls, do you want payments to wait, or lose some info lines? Errors?” |
| 3–5 min | Sketch Logger, LogSystem, Sink, Record, and a formatter. Say why there is no global. |
“The tests want to see what was logged, so the system is an object main makes.” |
| 10–15 min | Write Record, Sink, Logger::log, and dispatch. State INV-4 and INV-6. Show the escaped newline. |
“A formatter escapes control characters, so a user’s name cannot write a fake ERROR line.” |
| 10–15 min | Write AsyncSink: the bounded queue, write’s drop-or-wait, run writing outside the lock, flush waiting for a target, the draining destructor. |
“The worker unlocks before the slow write; otherwise a slow disk blocks every thread that logs.” |
| About 5 min | Take the change: fields, JSON, rotation. Or concurrency: what each lock guards, and why a sink must not log. | “Adding a member to Record without an initializer makes the compiler list every place that builds one.” |
What is usually expected at each level
| Level | Usually expected |
|---|---|
| Junior | Levels and a level check; a logger with a name; more than one destination behind an interface; a format with the time; a lock so that lines do not mix. |
| Mid-level | All of the above, plus: a level per logger that changes at run time; formatters separate from sinks; no global, with loggers passed in; lazy messages; escaping; logging that never throws; tests with a memory sink and a clock. |
| Senior | All of the above, plus: an asynchronous sink with a bounded queue and a stated policy when it is full; counts for what was dropped; flush and shutdown that are guaranteed; the worker writing outside the lock; deterministic tests of a full queue. |
These are this site’s judgement of common practice, as on How to approach a case study, not any company’s rubric.
Production limitations
Section titled “Production limitations”- No configuration. Routes, levels, and formats are set in code.
- Fixed routes. A sink cannot be added, removed, or changed while the program runs.
- Flat names. No logger hierarchy, no wildcard levels.
- The console is synchronous. A blocked terminal blocks warnings and errors.
- Drops are counted, not written. Nothing in the log says “37 lines were dropped here”. The exercise below adds it.
- No timeouts. An error waiting for room, and
flush, wait as long as the destination takes. A destination that never returns blocks them for ever. - No
fsync, and a crash loses the queue. - No source location. Lines do not say which file and line logged them.
- In the text formats, a message can look like a field. The message
charged order=99reads like a field; a person can tell, a program cannot. Use JSON for anything a program reads (ac_9_4shows both). - Invalid UTF-8 makes invalid JSON. Bytes from 0x80 up are copied as they are.
- Duplicate keys are kept. Two
orderfields make a JSON object with twoorderkeys, which many JSON readers handle by keeping the last. - Rotation is simple. By size only, not by time; one process per
file; old files are not compressed. While rotations keep failing,
every write fails and is lost. A full disk can leave a cut line at the
end of a file; a
FileSinkopens the same file again in append mode, so its next line can join the cut one. If a rotation stops part way, the old files may have moved up withoutapp.logmoving, so one old file can be lost early. - Unsigned and
long longvalues need a cast tostd::int64_tbefore they can be a field. - Performance was not measured. NFR-2 is a property of the code (one relaxed load), not a benchmark.
Traceability
Section titled “Traceability”| Requirement | Design element | Code | Tests | Status |
|---|---|---|---|---|
| FR-1 named loggers | LogSystem::logger, std::map of loggers |
step 1 log_system.cpp |
ac_1_2_the_same_name_gives_the_same_logger |
Tested |
| FR-2 levels, changeable | Logger::level_, enabled, set_level |
step 1 log_system.hpp |
ac_1_1_…, ac_1_3_a_level_can_change_while_the_program_runs |
Tested |
| FR-3 sinks with a minimum | Route, dispatch, Sink |
step 1 log_system.cpp, sinks.hpp |
ac_2_1_…, ac_2_2_…, ac_5_1_a_file_sink_appends_whole_lines |
Tested |
| FR-4 formats, no forged lines | format_line, format_short, escape_control |
step 1 format.cpp |
ac_3_1_the_two_formats_are_exact, ac_3_2_a_message_cannot_start_a_line_of_its_own |
Tested |
| FR-5 asynchronous, bounded | AsyncSink::write, run |
step 1 async_sink.cpp |
ac_6_1_…, ac_6_2_…, ac_6_3_…, inv_accepted_plus_dropped_is_everything_written |
Tested |
| FR-6 flush and shutdown | AsyncSink::flush, ~AsyncSink, ~LogSystem |
step 1 async_sink.cpp, log_system.cpp |
ac_7_1_…, ac_7_2_…, ac_7_3_destroying_an_async_sink_writes_its_queue_first |
Tested |
| FR-7 failures never thrown | Logger::log, dispatch, flush, failures |
step 1 log_system.cpp |
ac_8_1_a_failure_never_reaches_the_caller, an_async_sink_counts_an_inner_failure_and_carries_on, ac_8_2_a_file_that_cannot_be_written_says_so_at_once_and_recovers |
Tested |
| NFR-1 thread safety | atomic level, per-sink locks, one queue | all of step 1 | inv_many_threads_each_record_once_and_in_order, inv_lines_from_many_threads_never_interleave; tsan preset |
Tested |
| NFR-2 cheap when off | one relaxed load; lazy message | Logger::log |
ac_4_1_a_disabled_message_is_never_built; no timing measured |
Partly |
| NFR-3 bounded memory | capacity_ |
AsyncSink::write |
ac_6_3_… (high_water), inv_accepted_plus_dropped_… |
Tested |
| NFR-4 testable, no globals | LogSystem made in main, Clock |
step 1 log_system.hpp, record.hpp |
every test makes its own system | Tested |
| NFR-5 safe output | escape_control, text_key, needs_quotes, json_string |
format.cpp (both steps) |
ac_3_2_…, ac_9_3_…, ac_9_4_… |
Tested |
| FR-8 fields | Field, Value, Record::fields |
step 2 record.hpp, log_system.hpp |
ac_9_1_…, ac_9_2_an_async_sink_carries_the_fields (step 2) |
Tested |
| FR-9 key=value and JSON | format_fields, format_json |
step 2 format.cpp |
ac_9_3_text_lines_show_fields_as_key_value, ac_9_4_json_lines_are_exact_and_cannot_be_confused (step 2) |
Tested |
| FR-10 rotating file | RotatingFileSink |
step 2 sinks.cpp |
ac_10_1_… to ac_10_5_…, a_rotation_with_no_current_file_starts_a_new_one, rotating_sink_setup_mistakes_are_exceptions (step 2) |
Tested |
Exercise
Section titled “Exercise”Exercise: Say in the log that lines were dropped
Operators reading the file cannot tell that lines are missing; the drop
count is only in stats(). Add a line such as
WARN log: 37 record(s) dropped to the file, written where the gap
is: just before the first record accepted after the drops.
- Which class should write it:
Logger,LogSystem, orAsyncSink? Why not log it through aLogger? - What time should the line have, and where does it come from?
- Where in the code does it go, and when exactly is it written?
- How would you test it without timing?
Show the explained answer
-
AsyncSink. It is the only class that knows a drop happened, and the line belongs to the same destination the records were dropped from. It must not go through aLogger: that would be a sink logging through its own system, which can deadlock (see Concurrency and shutdown). It can build aRecorditself and write it toinner_directly, from the worker. -
The time the gap ended.
AsyncSinkhas no clock, and it does not need one: the first record accepted after the drops already carries a time, the moment the gap ended. Using it keeps the tests exact. Drops at the very end, with no record after them, can use the time of the last record dropped. -
With the next record accepted. Count the drops not yet reported, and store that count in the queue with the next record that gets in. The worker writes the notice just before that record, which puts it exactly where the gap is: after the last line before the drops, and before the first line after them. Drops that no record follows are still counted when the worker stops; the destructor, after the join, writes a last notice for them. A sketch:
IllustrativeA fragment for explanation; not compiled on its own.
// Each queue entry now carries the number of records dropped just// before it, so the notice is written in the right place.struct Queued {Record record;std::uint64_t dropped_before = 0; // drops just before this record};std::deque<Queued> queue_;std::uint64_t unreported_ = 0; // dropped, not yet attached to a recordTimestamp last_dropped_{};// In write, when a record is dropped:++stats_.dropped;++unreported_;last_dropped_ = record.time;// ...and when one is accepted. std::exchange(unreported_, 0) returns// the old count and sets unreported_ to 0, in one expression: the// drops are attached to this record and are not reported twice.queue_.push_back({std::move(copy), std::exchange(unreported_, 0)});// In run, outside the lock, before the record itself:if (next.dropped_before > 0) write_notice(next.dropped_before, next.record.time);inner_->write(next.record);// In the destructor, after worker_.join():if (unreported_ > 0) write_notice(unreported_, last_dropped_);// Writes "N record(s) dropped" at warn. Called only by the worker (or// by the destructor after the join), so it never runs beside a write.void AsyncSink::write_notice(std::uint64_t count, Timestamp time) noexcept {try {inner_->write(Record{Level::warn, "log",std::to_string(count) + " record(s) dropped", time});} catch (...) {// not one of the accepted records, so not counted in failed}}A notice is not an accepted record, so it is not counted in
writtenandflushneeds no change. But the sink now receives more lines than were accepted. Built into step 1, this answer makesinv_accepted_plus_dropped_is_everything_writtenfail, because it checks that the memory sink holds exactlyacceptedrecords; that check has to skip the notices. -
With the gate. Hold the worker on
r1asac_6_2does, queuer2andr3, writer4andr5(both dropped), open the gate and flush, then writer6and flush again. The messages must ber1,r2,r3,2 record(s) dropped,r6. A second test drops a record with nothing after it, destroys the sink, and expects the notice as the last message. Both tests, and the sketch above, were built into a copy of step 1 and pass.
Summary
Section titled “Summary”- A logging library is a few small parts: loggers decide, the log system routes, sinks write, formatters format. Each can be tested alone.
- “Logging must never fail a payment” means every logging call catches, counts, and carries on; the count is how anyone finds out.
- The log system is made in
mainand loggers are passed in. Tests get their own system and a memory sink; shutdown order is visible. - Escape control characters in the formatter, so no message can write a line of its own.
- An asynchronous sink is a Decorator with a bounded queue. Its worker
writes outside the lock, its
flushwaits for a target read on entry, and its destructor drains the queue before the thread stops. - When the queue is full, decide by level and count what is dropped.
- A test sink that blocks until the test opens it makes “the queue is full” a fact instead of a race.
- Adding a member without a default lets the compiler list every place
that builds the struct; a
std::visitwhose lambdas take exact types lists every place that must handle a new kind. Formatters that ignore a new member are found only by tests. - A buffered file reports a full disk late. Flush each line, and close and reopen after a failure, so the failure is charged to the right line and the log recovers.