Observability
What you will learn on this page
Section titled “What you will learn on this page”- What the three common kinds of record, logs, metrics, and traces, are each good for, and what each costs. Together they give a program its Observability.
- How to give a component’s core an observability port: a small interface it calls with events in its own words, so that the log format, the metric names, and the tracing system are decisions of adapters, not of the core.
- How to write log lines that a program can parse and a caller cannot forge, and metrics whose memory does not grow with traffic (Cardinality (of a metric)).
- Why recording must never change a result, and how
noexceptand a guarded adapter make that an explicit, tested part of the design. - How to test what a component reports, with a fake for the port and a manual clock.
The problem: a service that has to explain itself
Section titled “The problem: a service that has to explain itself”A shipping company runs a quote service. A caller sends a request ID, a carrier’s name, and a parcel’s weight; the service asks the carrier’s rate system for a price, adds a handling fee, and answers. Carriers are reached over a network, so they are sometimes slow and sometimes do not answer at all.
The service works in tests. In production, the people who run it ask questions the code does not answer by itself:
- “A customer says request
r-1003failed. What happened to it?” - “What fraction of quotes failed in the last hour, and why?”
- “Quotes are slow today. Is it us, or one of the carriers?”
Nobody can attach a debugger to a production service and wait for the problem to happen again. The program has to record enough, while it runs, to answer questions nobody has asked yet, and it has to do that without slowing down, failing, or becoming hard to change.
Three kinds of record
Section titled “Three kinds of record”| Kind | What it is | Answers questions like | Costs |
|---|---|---|---|
| Log | One line per notable event, with its details | “What happened to request r-1003?” |
Grows with traffic; every line is written, shipped, stored, and searched |
| Metric | A number kept in memory and read from time to time: a count, or a distribution of durations | “How many quotes failed in the last hour?” “How slow is the slowest 1%?” | Fixed memory for each name and label combination; no details about any single request |
| Trace | The timed steps of one request, linked by a shared ID | “Which step made this request slow?” | Like logs, so often only some requests are kept |
They are not alternatives. A metric shows that failures went up at 10:40; a trace shows that the failing requests all waited on one carrier; the log lines of one of those requests show the carrier’s error message. Each kind is cheap for its own questions and expensive or useless for the others: counting failures by reading every log line works, but costs far more than a counter.
Requirements
Section titled “Requirements”| # | Requirement | Design consequence |
|---|---|---|
| R1 | Everything one request causes can be found together | Every record carries the caller’s request ID; spans use it as their trace ID |
| R2 | Operators can count outcomes and see the spread of carrier latency, cheaply | Counters labelled by outcome; a latency histogram with fixed buckets |
| R3 | Recording never changes a quote’s result, even if a log stream fails | The port is noexcept; the adapter guards each sink and counts what it loses |
| R4 | The core can be tested, and changed, without any log format or metric name | The core reports events through a port in its own words; adapters own every format |
| R5 | Values from callers cannot forge or break log lines | Every log value is escaped |
| R6 | Memory use does not grow with traffic | Fixed buckets, labels from closed sets only, a bounded span recorder |
| R7 | Several threads may quote at once | The service keeps no state; every sink is thread-safe |
Step 1: the obvious version, and why it hurts
Section titled “Step 1: the obvious version, and why it hurts”The quickest way to answer “what happened?” is to write it down where
it happens. This fragment, the end of a quote function, was compiled
in a scratch file with both compilers, as a free function with the
validation and the carrier call left out; it was not run.
It works on the first day. Each problem appears later:
- The format becomes an interface. Someone writes an alert that
searches for
"quote "and" in ". Now changing the sentence breaks the alert, and nothing in the code says so. A test that wants to check what was reported has to capturestd::clogand parse English. - The core chose the destination and the library. Moving to a logging library, a file, or a metrics system means editing the business code, in every place that logs. This is logging-driven coupling: the most important code in the program depends on its least important detail.
- Time cannot be controlled. The duration comes from the real clock, so a test cannot check that a slow carrier is reported as slow without being slow itself.
- A caller can write to the log. A request ID containing a newline starts a new line with whatever text the caller chose, such as a fake error. This is log injection.
- The global map is a data race. Two threads quoting at once both
modify
g_quote_counts, which is undefined behaviour. Adding a mutex fixes the race but not the global: every test shares it. - Recording can fail the request. If
std::cloghas exceptions enabled and the write fails, or the map’s allocation fails, the exception escapes fromquote, and the customer gets an error because of a log line.
None of this is a reason not to record. It is a reason to separate what happened, which the core knows, from how it is recorded, which the core should not care about.
Step 2: the observability port
Section titled “Step 2: the observability port”In hexagonal architecture, the core owns the interfaces it needs, and adapters implement them. Observability is one more driven port. The core’s types come first:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// What a caller asks for: a price to send a parcel of this weight with// this carrier. Plain data, with no rules of its own; QuoteService checks// the weight.struct QuoteRequest { std::string request_id; // chosen by the caller; ties together everything one request causes std::string carrier; int weight_grams = 0;};
// A successful answer: the price, in whole cents so that no rounding// error can creep in, with the carrier it is for.struct Quote { std::string carrier; long long price_cents = 0;};
// The three ways a quote can fail to produce a price. invalid_weight: the// request was refused before any carrier was asked. no_rate: the carrier// answered, but has no price for this weight. carrier_unavailable: the// carrier could not be reached.enum class QuoteFailure { invalid_weight, no_rate, carrier_unavailable };
// Every quote ends as exactly one of these: a Quote, or a QuoteFailure// saying why there is none. A std::variant holds one of its listed types// at a time, so a caller has to check which one it got before reading a// price (std::get on the wrong type throws std::bad_variant_access).using QuoteResult = std::variant<Quote, QuoteFailure>;
// A short, fixed name for each outcome. The set is closed, so it is safe// to use as a metric label. Every name returned is a string literal, which// lives for the whole program, so the returned string_view never dangles.// constexpr lets the compiler run it at compile time too; noexcept says it// never throws.constexpr std::string_view outcome_name(const QuoteResult& result) noexcept { // holds_alternative asks "does the variant hold a Quote right now?". if (std::holds_alternative<Quote>(result)) return "ok"; // get_if returns a pointer to the QuoteFailure inside the variant, or // nullptr if it holds something else. Unlike std::get, it never throws. const QuoteFailure* failure = std::get_if<QuoteFailure>(&result); if (failure == nullptr) return "unknown"; // only if the variant lost its value switch (*failure) { // one case per enumerator; with warnings on, a missing one is reported case QuoteFailure::invalid_weight: return "invalid_weight"; case QuoteFailure::no_rate: return "no_rate"; case QuoteFailure::carrier_unavailable: return "carrier_unavailable"; } return "unknown"; // reached only by a value outside the three enumerators}outcome_name gives each outcome a short, fixed name. The set is
closed, which matters later: a fixed set of values is safe to use as a
metric label.
The ports:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The one exception a carrier is expected to throw: it could not be// reached (a timeout, a refused connection). Deriving from// std::runtime_error gives it a message, read with what(). The `using`// line borrows runtime_error's constructors, so it can be built straight// from a message string.class CarrierUnavailable : public std::runtime_error {public: using std::runtime_error::runtime_error;};
// Driven port: a carrier's price list, usually reached over a network.// The core only knows this interface; a real network client, or a fake in// a test, implements it. "= 0" makes each function pure virtual: there is// no body here, and every implementation must supply one. The virtual// destructor lets an implementation be destroyed safely through a base// pointer.class CarrierRates {public: virtual ~CarrierRates() = default; // The price, or nullopt if the carrier has no rate for this weight. // Throws CarrierUnavailable if the carrier cannot be reached. virtual std::optional<long long> rate_cents(const std::string& carrier, int weight_grams) = 0;};
// Driven port: time, so that durations can be tested. The core asks this// object for the time instead of calling std::chrono::steady_clock::now()// itself, so a test can hand it a clock that moves only when told.class Clock {public: virtual ~Clock() = default; [[nodiscard]] virtual std::chrono::steady_clock::time_point now() const = 0;};
// The observability port: what happened, in the core's own words.// noexcept is part of the contract: recording an event must never turn// into a failed quote, so an adapter has to handle its own failures.// The core calls these three functions; it never learns what, if// anything, is recorded. Each receives the request, so every record can// carry its request ID, and a duration, measured by the core's Clock.class QuoteEvents {public: // A short name for the clock's duration type, which counts clock ticks // (usually nanoseconds). using Duration = std::chrono::steady_clock::duration;
virtual ~QuoteEvents() = default; // The carrier replied, with a price or with "no rate". virtual void carrier_answered(const QuoteRequest& request, Duration took) noexcept = 0; // The carrier could not be reached; `reason` is the exception's message, // valid only during the call, so an adapter that keeps it must copy it. virtual void carrier_failed(const QuoteRequest& request, Duration took, std::string_view reason) noexcept = 0; // The request has its final answer; called once per answered request. virtual void quote_finished(const QuoteRequest& request, const QuoteResult& result, Duration took) noexcept = 0;};
// For programs and tests that record nothing. Each body is empty: the// events are accepted and ignored. Parameters have no names because they// are never used. `final` means no class may derive from this one.class NoQuoteEvents final : public QuoteEvents {public: void carrier_answered(const QuoteRequest&, Duration) noexcept override {} void carrier_failed(const QuoteRequest&, Duration, std::string_view) noexcept override {} void quote_finished(const QuoteRequest&, const QuoteResult&, Duration) noexcept override {}};Each choice in QuoteEvents answers one of the problems in Step 1:
- Events, in the core’s words.
carrier_answered,carrier_failed,quote_finished: names from the problem, not from a logging library. There is no level, no format string, and no metric name. The core says what happened; whoever implements the port decides whether that becomes a log line, a counter, a span, all three, or nothing. - Typed arguments. The adapter receives the request, the result as
a
QuoteResult, and the duration as astd::chronoduration, not text. It can label a counter with the outcome or put the price in a log field without parsing anything (R4). noexceptis the contract. An implementation may not throw. The compiler enforces part of this: an override of anoexceptvirtual function must itself benoexcept(in a scratch file, GCC and Clang both rejected one that was not). It does not check the body. If an exception reaches anoexceptboundary at run time,std::terminateends the program, and the paths that throw, such as a full disk or a failed allocation, are exactly the ones that rarely run in tests. So every adapter must handle its own failures, which is where the knowledge is (R3), and those failure paths need tests of their own, as theBrokenBuftest below does.- A
Clockport. Durations come from a clock the core is given. The real one wrapsstd::chrono::steady_clock, which never goes backwards; the system clock can jump when the machine’s time is corrected, so it is wrong for measuring durations. NoQuoteEventsdoes nothing, for programs and tests that do not record. It is the Null Object form of the port.
The two clocks:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The real clock. steady_clock never goes backwards, unlike the system// clock, so it is the right one for measuring how long something took.class SteadyClock final : public Clock {public: [[nodiscard]] std::chrono::steady_clock::time_point now() const override { return std::chrono::steady_clock::now(); }};
// A clock that moves only when told to, for tests and for a demo whose// output must be the same on every run. Safe to read and advance from// several threads.//// The time is stored as a plain number of clock ticks since the clock's// starting point. It starts at 0 and only advance() changes it, so two// readings with no advance() between them are exactly equal, and a// duration measured across advance(40ms) is exactly 40 ms.class ManualClock final : public Clock {public: // Turns the tick count back into a time point: first a duration of // that many ticks, then the time point that far after the start. // load() reads the atomic number safely while another thread may be // changing it. [[nodiscard]] std::chrono::steady_clock::time_point now() const override { return std::chrono::steady_clock::time_point( std::chrono::steady_clock::duration(ticks_.load())); } // Moves the clock forward. by.count() is the step in ticks; += on a // std::atomic is one indivisible add, so two threads advancing at once // never lose a step. void advance(std::chrono::steady_clock::duration by) noexcept { ticks_ += by.count(); }
private: // rep is the number type steady_clock uses to count ticks. std::atomic<std::chrono::steady_clock::rep> ticks_{0};};ManualClock keeps its time in a std::atomic, so several threads
may read and advance it. A test or a demo moves it forward by exactly
as much as it wants.
Text description of the diagram
The core contains QuoteService and three ports it owns: QuoteEvents, which is noexcept, CarrierRates, and Clock. QuoteService uses all three. Outside the core are the adapters. TelemetryEvents implements QuoteEvents; it guards each sink and counts dropped records, and it writes to three sinks: EventLog, which writes key=value lines; Metrics, which holds counters and a histogram; and SpanRecorder, which is bounded. A carrier client implements CarrierRates, and SteadyClock or ManualClock implements Clock. The composition root creates and wires QuoteService and creates TelemetryEvents.
Diagram source (Mermaid)
flowchart LR
subgraph Core["core: knows no format"]
QS["QuoteService"]
QE[["QuoteEvents port<br/>noexcept"]]
CR[["CarrierRates port"]]
CL[["Clock port"]]
QS --> QE
QS --> CR
QS --> CL
end
subgraph Adapters["adapters"]
TE["TelemetryEvents<br/>guards each sink,<br/>counts dropped records"]
LOG["EventLog<br/>key=value lines"]
MET["Metrics<br/>counters, histogram"]
SP["SpanRecorder<br/>bounded"]
CAR["carrier client"]
SC["SteadyClock or ManualClock"]
end
TE -.->|"implements"| QE
CAR -.->|"implements"| CR
SC -.->|"implements"| CL
TE --> LOG
TE --> MET
TE --> SP
ROOT["composition root"] -->|"creates and wires"| QS
ROOT -->|"creates"| TEStep 3: the core reports what happened
Section titled “Step 3: the core reports what happened”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The use case. It holds references to its ports, so whoever creates it// (the composition root) must keep the carrier, clock, and events alive// for as long as the service is used. It keeps no other state, so one// service can be called from several threads if its ports allow it.class QuoteService {public: // The business rules: the heaviest parcel accepted (the ' only groups // digits, so this is 30000), and a fee added to every carrier price. static constexpr int max_weight_grams = 30'000; static constexpr long long handling_fee_cents = 99;
// Stores the three references; it copies nothing and owns nothing. QuoteService(CarrierRates& rates, const Clock& clock, QuoteEvents& events) noexcept : rates_(rates), clock_(clock), events_(events) {}
// Checks the weight, asks the carrier if it is valid, reports the // result through the events port, and returns it. Expected failures // come back as a QuoteFailure; only an exception other than // CarrierUnavailable escapes. QuoteResult quote(const QuoteRequest& request);
private: // The carrier call and its two events, separated out so quote() reads // as "check, ask, report". QuoteResult ask_carrier(const QuoteRequest& request);
// References, not copies or owning pointers: the service uses objects // that someone else created and keeps alive. CarrierRates& rates_; const Clock& clock_; QuoteEvents& events_;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The use case. Reads the clock once at the start and once at the end, so// the reported duration covers the whole request.QuoteResult QuoteService::quote(const QuoteRequest& request) { const auto started = clock_.now(); // Assume the weight is refused; only a weight from 1 to 30000 grams // replaces this with the carrier's answer. QuoteResult result = QuoteFailure::invalid_weight; if (request.weight_grams > 0 && request.weight_grams <= max_weight_grams) { result = ask_carrier(request); } // One event for every request that gets an answer, whatever it is: the // summary that logs, metrics, and traces are built from. An unexpected // exception skips it; the code that catches the exception reports it. // Subtracting two time points gives a duration: how long it took. events_.quote_finished(request, result, clock_.now() - started); return result;}
// Calls the carrier and turns its answer into a QuoteResult. Exactly one// carrier event is reported: carrier_answered if it replied, or// carrier_failed if it threw CarrierUnavailable. Any other exception is// not caught here, so it leaves this function, and quote(), with no event.QuoteResult QuoteService::ask_carrier(const QuoteRequest& request) { const auto called = clock_.now(); try { const std::optional<long long> rate = rates_.rate_cents(request.carrier, request.weight_grams); // "No rate" is an answer: the carrier worked, the service did not. events_.carrier_answered(request, clock_.now() - called); if (!rate) return QuoteFailure::no_rate; // an empty optional: no price // *rate reads the price out of the optional, which is known to hold // one here. The Quote converts to a QuoteResult on the way out. return Quote{request.carrier, *rate + handling_fee_cents}; } catch (const CarrierUnavailable& error) { // An expected failure: report it with the exception's message, and // return it as a value. error.what() is valid until this block ends, // which covers the call. events_.carrier_failed(request, clock_.now() - called, error.what()); return QuoteFailure::carrier_unavailable; }}How this code works: QuoteService::quote and ask_carrier
- Start the clock.
quotereads the clock intostarted. - Assume the worst.
resultstarts asinvalid_weight. Only a weight from 1 to 30000 grams replaces it, by callingask_carrier. A weight of 0 skips the carrier entirely. - Ask the carrier.
ask_carrierreads the clock again intocalled, then callsrate_centsinside atry. Exactly one carrier event follows:- the carrier returned, with or without a price:
carrier_answered, thenno_ratefor an emptystd::optional, or aQuotewith the price plus the 99 cent fee; - it threw
CarrierUnavailable:carrier_failed, with the exception’s message, thencarrier_unavailable; - it threw anything else: there is no matching
catch, so the exception leavesask_carrierand thenquote, and no event is reported at all.
- the carrier returned, with or without a price:
- Report the summary. Back in
quote,quote_finishedis called with the result and the whole duration,clock_.now() - started. - Return the result to the caller.
A trace with the demo’s five requests. The demo’s carriers move the manual clock by a fixed step per call (40, 120, or 2000 ms), so every duration is exact:
| Request | Carrier, weight | Carrier event | Result | quote_finished took |
|---|---|---|---|---|
r-1001 |
swiftpost, 1200 g | answered, 40 ms | Quote, 450 + 120 + 99 = 669 |
40 ms |
r-1002 |
parcelco, 15000 g | answered, 120 ms | no_rate (above 10000 g) |
120 ms |
r-1003 |
slowboat, 800 g | failed, 2000 ms, timed out | carrier_unavailable |
2000 ms |
r-1004 |
swiftpost, 0 g | none: never called | invalid_weight |
0 ms |
r-1005 |
swiftpost, 500 g | answered, 40 ms | Quote, 450 + 50 + 99 = 599 |
40 ms |
Every request ends with exactly one quote_finished, and only the four
that reached a carrier have a carrier event.
The business rules are a few lines; the reporting adds three event calls and the clock readings, and none of them is about a format. Some details are decisions:
- One
quote_finishedfor every answer. Whatever the outcome, valid or not, the request produces exactly one summary event. That is the event that logs, counters, and the outer span are built from, so “how many quotes” has one answer. - “No rate” is an answer, not a failure. The carrier worked and
said no, so
carrier_answeredreports it. OnlyCarrierUnavailablemeans the carrier failed. Mixing the two would make a carrier that has no rates for heavy parcels look broken. - The failure reason travels as a
string_view.error.what()stays valid while thecatchblock runs, which covers the call; an adapter that wants to keep the text must copy it. - An unexpected exception skips
quote_finished. If the carrier adapter throws something other thanCarrierUnavailable, such as a bug’sstd::logic_error, it propagates to the caller, and the code that catches it reports it. The core does not pretend to know what went wrong. A test below fixes this behaviour, so changing it is a visible decision.
The service holds references to its ports and no other state, so one service may be shared by several threads, if its ports are thread-safe (R7).
Step 4: logs that a program can read and a caller cannot forge
Section titled “Step 4: logs that a program can read and a caller cannot forge”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A value as it may appear in a log line. Plain values, such as r-1001,// are written as they are. Anything else is quoted, with quotes,// backslashes, and control characters escaped, so that a value can// never end the line or pretend to be another field. Returns a new string;// `raw` is only read.[[nodiscard]] std::string log_value(std::string_view raw);
// One key=value pair of a log line. The key is a string_view because keys// are string literals in the code, which live for the whole program; the// value is a std::string because it is often built for the call, such as// a number turned into text.struct LogField { std::string_view key; // fixed by the code, never by input std::string value;};
// A structured log: one line per record, made of key=value fields, so// that a program can filter it and a person can still read it.class EventLog {public: // The stream must outlive the log. explicit EventLog(std::ostream& out) noexcept : out_(out) {}
// Writes one whole line. Throws if the stream fails; several threads // may write at once, and their lines never interleave. // std::initializer_list lets a caller pass the fields as a brace list: // write("info", "x", {{"request_id", id}, {"took_ms", "40"}}). void write(std::string_view level, std::string_view event, std::initializer_list<LogField> fields);
private: std::mutex mutex_; // lets one thread at a time use out_ std::ostream& out_; // not owned: std::cout, a file, or a test's string stream};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Two passes over the value. The first decides whether it needs quotes at// all; the second, only for values that do, copies it character by// character, replacing each dangerous one with an escape sequence.// plain(), a helper earlier in this file, is true only for letters,// digits, and - _ . : /std::string log_value(std::string_view raw) { // An empty value is quoted, as "", so the reader still sees a value. // Then one character that is not plain is enough to need quotes; the // `||` keeps the flag true once it is set. bool needs_quotes = raw.empty(); for (const char c : raw) needs_quotes = needs_quotes || !plain(c); if (!needs_quotes) return std::string(raw); // the common case: copied as it is
std::string out = "\""; // the opening quote for (const char c : raw) { // char may be signed, so a byte above 0x7f could look negative. // Converting to unsigned char gives its value from 0 to 255. const auto byte = static_cast<unsigned char>(c); // In C++ source, '\\' is one backslash character and "\\n" is a // backslash followed by n: the two characters a reader sees. if (c == '"' || c == '\\') { out += '\\'; // a backslash first, then the character itself out += c; } else if (c == '\n') { out += "\\n"; // a real line break becomes the visible pair \n } else if (c == '\r') { out += "\\r"; } else if (c == '\t') { out += "\\t"; } else if (byte < 0x20 || byte == 0x7f) { // Any other control character (below 0x20, or DEL) is written // as four visible characters, such as \x07 for the bell. // %02x prints the byte as two hex digits; the array has room // for the four characters plus the '\0' that ends the string. char hex[5]; std::snprintf(hex, sizeof hex, "\\x%02x", static_cast<unsigned>(byte)); out += hex; } else { out += c; // printable ASCII, or part of a UTF-8 character } } out += '"'; // the closing quote return out;}
// Builds one line, "level=... event=..." and then " key=value" for each// field, with every value passed through log_value; keys are trusted// because the code chose them. Then writes it under the lock.void EventLog::write(std::string_view level, std::string_view event, std::initializer_list<LogField> fields) { // Build the whole line first, so the lock covers one write. std::string line = "level="; line += level; line += " event="; line += event; for (const LogField& field : fields) { line += ' '; line += field.key; line += '='; line += log_value(field.value); } line += '\n'; // the only newline in the line: every value's newlines were escaped
// scoped_lock locks the mutex now and unlocks it when `lock` goes out // of scope at the closing brace, even if a throw leaves early. const std::scoped_lock lock(mutex_); // ostream::write takes the length as std::streamsize, a signed type, // hence the cast from size(), which is unsigned. out_.write(line.data(), static_cast<std::streamsize>(line.size())); out_.flush(); // push the line out now, so a crash loses at most this one // `!out_` is true if the stream has failed. A stream set to throw has // already thrown inside write or flush; this covers the default kind, // which only sets a flag. if (!out_) throw std::runtime_error("event log: the stream failed");}How this code works: log_value on a hostile request ID
Take the demo’s last request ID: the text r-1005, a real line break,
then level=error event=fake.
- First pass: does it need quotes?
needs_quotesstarts asfalse, because the value is not empty. The characters ofr-1005are all plain. The line break is not, so the flag becomestrueand staystruefor the rest of the loop. - Second pass: copy and escape.
outstarts as one". Then each character is copied, except the ones theifchain catches:r-1005is copied as it is;- the line break matches
c == '\n', so the two visible characters\andnare added instead; level=error event=fakeis copied as it is. The=and the space are not plain, which is why the value needed quotes, but inside quotes they are harmless, so they are not escaped.
- Close the quote. A final
"is added.
The result is "r-1005\nlevel=error event=fake", all on one line, which
is what the demo prints. A reader that splits the log at line breaks sees
one record whose request_id happens to contain the text level=error,
not a second record.
A plain value such as r-1001 never reaches the second pass: the first
pass finds nothing to worry about, and it is returned unchanged.
Structured lines. Each record is one line of key=value fields,
such as level=info event=quote_finished request_id=r-1001 .... A
program can split it into fields without guessing at sentences, so an
alert can ask for event=carrier_failed and keep working when someone
adds a field. Many systems write JSON objects instead; the idea is the
same, and only the adapter would change.
Escaping. Keys are fixed by the code. Values often come from
callers, so log_value treats them as hostile: a value made only of
letters, digits, and - _ . : / is written as it is, and anything else
is quoted, with " and \ escaped, newlines, tabs, and carriage
returns written as \n, \t, \r, and other control characters as
\xHH. A value can then never end a line or start a field of its own,
for any reader that splits lines at \n (R5). Bytes above 0x7f are
kept, so that UTF-8 names stay readable. That is a trade-off: some
viewers treat Unicode characters such as U+2028 (line separator) as a
line break, or reorder text around direction marks such as U+202E, so
a log read in such a viewer can still be made to look misleading. A
stricter adapter escapes every byte above 0x7f, or checks that the
value is valid UTF-8 and escapes those characters.
One write per line. write builds the whole line before it takes
the lock, so threads that write through one EventLog never
interleave halves of lines, and the lock is held only for the write
itself. Code that writes to the same stream directly, as the demo’s
headings do, bypasses the lock; that is fine in one thread, and a
data race otherwise.
Failures are reported, not hidden. If the stream fails, write
throws, whether the stream was set to throw or only sets its failure
flag. Hiding the failure here would make the log lose records with no
trace; deciding what a failure costs is the adapter’s job, in Step 7.
What to log. This design logs one summary line for every request and one warning for every carrier failure, and nothing for each successful carrier call; the trace has those. Logging every step of every request is the usual way logs become too expensive to keep. Equally important is what not to log: passwords, tokens, and personal data stay out of log lines, because logs are copied to many places and kept for a long time. A request ID is safe to log because it was made to be.
Step 5: metrics that cost the same at any traffic
Section titled “Step 5: metrics that cost the same at any traffic”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Numbers that are cheap to keep for every request and are read as// totals: counters, and one latency histogram. Thread-safe.class Metrics {public: // A counter's name includes its labels, as in quotes_total{outcome="ok"}. // A name seen for the first time starts at 0. `by = 1` is a default // argument: add(name) adds one. void add(const std::string& counter, long long by = 1); // Compared with the bounds at full precision: a 50.9 ms call is not // counted as at most 50 ms. void observe_carrier_latency(std::chrono::steady_clock::duration took);
// The counter's current value, or 0 for a name never added to. [[nodiscard]] long long counter(const std::string& name) const; // How many latencies have been observed in total. [[nodiscard]] long long latency_count() const; // Every counter in name order, then the histogram, one per line. [[nodiscard]] std::string render() const;
// Upper bounds of the histogram's buckets, in milliseconds. A fixed // set of buckets keeps the memory fixed, however many requests come. static constexpr std::array<long long, 3> latency_bounds_ms{50, 250, 1000};
private: // mutable: the const readers above must still lock it, and locking // changes the mutex. mutable std::mutex mutex_; // A std::map keeps its keys sorted, which is why render() lists the // counters in name order. std::map<std::string, long long> counters_; // How many observations were at most each bound; the last is +Inf. // Four slots: three bounds plus one that counts everything. The {} // starts every slot at 0. std::array<long long, latency_bounds_ms.size() + 1> at_most_{}; // The total of every observed latency, at the clock's full precision. std::chrono::steady_clock::duration latency_sum_{};};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Every member function takes the same lock first, so a reader never sees// a half-finished update, and two threads never update at once.void Metrics::add(const std::string& counter, long long by) { const std::scoped_lock lock(mutex_); // map's [] finds the counter, or inserts it with the value 0 if this is // the first time the name is seen, and returns a reference to it. counters_[counter] += by;}
// Adds one observation to every bucket whose bound it fits under, so the// buckets are cumulative, and always to the last, +Inf, bucket.void Metrics::observe_carrier_latency(std::chrono::steady_clock::duration took) { const std::scoped_lock lock(mutex_); for (std::size_t i = 0; i < latency_bounds_ms.size(); ++i) { // The bound is turned into a chrono duration and compared with // `took` as it is: chrono converts both to the finer unit, so // nothing is rounded. 50.9 ms is not <= 50 ms. if (took <= std::chrono::milliseconds(latency_bounds_ms[i])) ++at_most_[i]; } ++at_most_.back(); // back() is the last slot: +Inf counts every observation latency_sum_ += took;}
long long Metrics::counter(const std::string& name) const { const std::scoped_lock lock(mutex_); // find, not [], because [] would insert the name, and a reader must not // create counters. end() means "not found"; found->second is the value. const auto found = counters_.find(name); return found == counters_.end() ? 0 : found->second;}
long long Metrics::latency_count() const { const std::scoped_lock lock(mutex_); return at_most_.back();}
// Writes everything as text, one "name value" line each, in the shape// that monitoring systems such as Prometheus read: the counters, then one// line per bucket, then the count and the sum.std::string Metrics::render() const { const std::scoped_lock lock(mutex_); std::string out; // Each map entry is a key and value pair; [name, value] unpacks it into // two names (a structured binding). for (const auto& [name, value] : counters_) { out += name + ' ' + std::to_string(value) + '\n'; } for (std::size_t i = 0; i < latency_bounds_ms.size(); ++i) { out += "carrier_latency_ms_bucket{le=\"" + std::to_string(latency_bounds_ms[i]) + "\"} " + std::to_string(at_most_[i]) + '\n'; } out += "carrier_latency_ms_bucket{le=\"+Inf\"} " + std::to_string(at_most_.back()) + '\n'; out += "carrier_latency_ms_count " + std::to_string(at_most_.back()) + '\n'; // Only now is the sum converted to milliseconds; duration_cast drops // any fraction of a millisecond. const auto sum_ms = std::chrono::duration_cast<std::chrono::milliseconds>(latency_sum_); out += "carrier_latency_ms_sum " + std::to_string(sum_ms.count()) + '\n'; return out;}How this code works: Filling the latency histogram
at_most_ has four slots, one for each bound (50, 250, and 1000 ms)
and a last one for +Inf. observe_carrier_latency adds one to every
slot whose bound the duration fits under, and always to the last one.
So a slot holds “how many calls took at most this long”, and each slot
is at least as large as the one before it.
The demo observes four carrier calls, in this order (r-1004 never
reached a carrier):
| Call | Took | le="50" |
le="250" |
le="1000" |
+Inf |
latency_sum_ |
|---|---|---|---|---|---|---|
r-1001 |
40 ms | 1 | 1 | 1 | 1 | 40 ms |
r-1002 |
120 ms | 1 | 2 | 2 | 2 | 160 ms |
r-1003 |
2000 ms | 1 | 2 | 2 | 3 | 2160 ms |
r-1005 |
40 ms | 2 | 3 | 3 | 4 | 2200 ms |
The last row is exactly what the demo’s metrics print. render writes
the four slots as the four bucket lines, the last slot again as the
count, and the sum converted to whole milliseconds.
Counters only go up. A monitoring system reads them every few
seconds and works out rates from the differences, so the program
never has to know what “the last hour” means. quotes_total has one
label, the outcome, written into the counter’s name as
quotes_total{outcome="ok"}; each label value is a separate series.
A histogram answers “how slow?” without keeping every duration.
Each bucket counts the observations at most its bound, so the buckets
are cumulative: le="250" includes everything in le="50". +Inf
counts everything, and the sum gives the average. From the buckets, a
monitoring system can estimate, for example, that 99% of carrier
calls took at most 250 ms. The bounds are fixed when the program is
written, so the memory is fixed too (R6). Choosing them is a design
decision: they should sit around the durations that matter, here a
fast answer, a slow one, and the point at which callers give up.
Cardinality. Every distinct label value creates a series. This
program keeps each one for as long as it runs, and the monitoring
system stores each one for as long as it keeps data. An outcome
has four values. A request ID has one value per request, so as a label
it would make the metric grow without limit. The carrier name is the
subtle case: it looks like a small set, but it comes from the request,
so any caller can create a new series by inventing a name. That is why
carrier_errors_total has no carrier label. The safe rule: label
only with values from a closed set the code controls; put everything
else in logs or traces, which are made for details.
Failures are timed too. A carrier that times out after two seconds is the slowest call of all. If only answers were timed, the histogram would look better exactly when things are worst.
Compare at full precision. observe_carrier_latency takes the
clock’s own duration and compares it with each bound, and converts to
milliseconds only when it prints the sum. Converting first would be a
quiet bug: duration_cast truncates, so a 50.9 ms call would become
50 ms and be counted as at most 50 ms. A test checks exactly that
case. (Spans and log lines show whole milliseconds, which is fine for
reading.)
Step 6: traces that follow one request
Section titled “Step 6: traces that follow one request”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One timed step of one request. Every span of a request has the same// trace_id, and names its parent, so the steps can be put back together.struct Span { std::string trace_id; // the request ID, shared by all spans of one request std::string name; // the step: "quote" or "carrier.rates" here std::string parent; // empty for the request's outermost span std::chrono::milliseconds took{}; // whole milliseconds, for reading bool ok = true; // false if the step failed to do its job};
// Keeps finished spans, up to a fixed number, for a test or the demo to// read. A real recorder would send them to a tracing system instead.class SpanRecorder {public: explicit SpanRecorder(std::size_t capacity) : capacity_(capacity) {}
// False, and the span is not kept, if the recorder is full. The span is // taken by value and moved into the store, so the caller's copy is not // needed afterwards. It never holds more than `capacity` spans, so its // memory has a fixed upper limit. [[nodiscard]] bool record(Span span); // A copy of every span kept so far, taken under the lock, so the caller // can read it while other threads go on recording. [[nodiscard]] std::vector<Span> spans() const;
private: mutable std::mutex mutex_; std::size_t capacity_; std::vector<Span> spans_;};A span is one timed step. Every span of one request shares a
trace ID, here the caller’s request ID (R1), and names its parent,
so a tool can draw the request as a tree: the quote span, and inside
it the carrier.rates span. Where the time went is then visible at a
glance; for r-1003, all 2000 ms are in the carrier call.
This recorder keeps finished spans in memory, up to a fixed number, for the demo and the tests to read. It is deliberately small. Real tracing systems add a unique ID to each span, start times, and propagation: passing the trace ID to the carrier in the network request, so that the carrier’s own spans join the same trace. OpenTelemetry is a widely used set of libraries for this, and W3C Trace Context defines a standard header for propagation; neither was used or tested here. With the port in place, using one of them would mean writing one new adapter.
Traces are expensive like logs, so systems often keep only a sample,
such as one request in a hundred, plus every request that failed.
record returns false when the recorder is full, and the adapter
counts the span as dropped, so a full recorder costs data but never
memory (R6).
Step 7: the adapter that must not fail
Section titled “Step 7: the adapter that must not fail”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Turns each event from the core into log lines, metrics, and spans.// The port is noexcept, so nothing may escape: each sink is called on// its own, a sink that fails is counted in dropped(), and the others// still record. The sinks must outlive this object.class TelemetryEvents final : public QuoteEvents {public: // Keeps references to the three sinks; owns none of them. TelemetryEvents(EventLog& log, Metrics& metrics, SpanRecorder& spans) noexcept : log_(log), metrics_(metrics), spans_(spans) {}
void carrier_answered(const QuoteRequest& request, Duration took) noexcept override; void carrier_failed(const QuoteRequest& request, Duration took, std::string_view reason) noexcept override; void quote_finished(const QuoteRequest& request, const QuoteResult& result, Duration took) noexcept override;
// How many records were lost because a sink failed or was full. [[nodiscard]] long long dropped() const noexcept { return dropped_.load(); }
private: // Runs one recording step, `record`, which is any callable (here always // a lambda) that returns true if it recorded and false if it did not. // A false result or any exception adds one to dropped_; nothing escapes. // Record&& in a template accepts any lambda without copying it. template <class Record> void guarded(Record&& record) noexcept;
EventLog& log_; Metrics& metrics_; SpanRecorder& spans_; // Atomic, because threads quoting at once may each drop a record; a // plain long long would be a data race. std::atomic<long long> dropped_{0};};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
template <class Record>void TelemetryEvents::guarded(Record&& record) noexcept { // Telemetry is never worth a failed quote: a full disk, a closed // stream, or a failed allocation costs one record, which is counted. try { // record() runs the lambda. It returns false when a sink refused, // as a full SpanRecorder does, without throwing. if (!record()) ++dropped_; } catch (...) { // `...` catches an exception of any type ++dropped_; }}
// Each event below is turned into a few separate recording steps, and each// step is a lambda handed to guarded(). [&] lets a lambda use the function's// parameters and members by reference; it runs at once, inside guarded(),// so those references are still valid. A step whose sink has no way to// refuse ends with `return true`: if it did not throw, it recorded.void TelemetryEvents::carrier_answered(const QuoteRequest& request, Duration took) noexcept { // whole_ms, a helper earlier in this file, truncates to whole ms. const std::chrono::milliseconds ms(whole_ms(took)); guarded([&] { metrics_.observe_carrier_latency(took); return true; }); // The braces build a Span field by field: trace_id, name, parent, // took, ok. Copying the request ID into it can allocate, which is why // this is inside a guard too. guarded([&] { return spans_.record({request.request_id, "carrier.rates", "quote", ms, true}); });}
void TelemetryEvents::carrier_failed(const QuoteRequest& request, Duration took, std::string_view reason) noexcept { const std::chrono::milliseconds ms(whole_ms(took)); guarded([&] { // A failure is worth a log line: a warning with the reason. log_.write("warn", "carrier_failed", {{"request_id", request.request_id}, {"carrier", request.carrier}, {"reason", std::string(reason)}, {"took_ms", std::to_string(ms.count())}}); return true; }); guarded([&] { // No carrier label: the name comes from the request, so as a // label it would let callers create any number of counters. metrics_.add("carrier_errors_total"); return true; }); guarded([&] { // Failures are timed too; leaving them out would hide timeouts. metrics_.observe_carrier_latency(took); return true; }); guarded([&] { return spans_.record({request.request_id, "carrier.rates", "quote", ms, false}); });}
void TelemetryEvents::quote_finished(const QuoteRequest& request, const QuoteResult& result, Duration took) noexcept { const std::chrono::milliseconds ms(whole_ms(took)); const std::string_view outcome = outcome_name(result); // refers to a string literal // A pointer to the Quote inside the result, or nullptr if it failed. const Quote* quote = std::get_if<Quote>(&result); guarded([&] { // The two calls differ only in the price field, which only a // successful quote has. if (quote != nullptr) { log_.write("info", "quote_finished", {{"request_id", request.request_id}, {"carrier", request.carrier}, {"outcome", std::string(outcome)}, {"price_cents", std::to_string(quote->price_cents)}, {"took_ms", std::to_string(ms.count())}}); } else { log_.write("info", "quote_finished", {{"request_id", request.request_id}, {"carrier", request.carrier}, {"outcome", std::string(outcome)}, {"took_ms", std::to_string(ms.count())}}); } return true; }); guarded([&] { // outcome_name has a closed set of values, so it is a safe label. metrics_.add("quotes_total{outcome=\"" + std::string(outcome) + "\"}"); return true; }); // A span reports whether the service worked. "No rate" and an invalid // weight are answers, not failures; only an unreachable carrier is. const bool worked = outcome != "carrier_unavailable"; guarded([&] { return spans_.record({request.request_id, "quote", "", ms, worked}); });}How this code works: One quote with a broken log
This is the BrokenBuf test further down: the log’s stream fails every
write and is set to throw, and the carrier always answers 500 cents.
carrier_answeredruns two guarded steps. The latency is added to the histogram, and the lambda returnstrue. Thecarrier.ratesspan is recorded;recordreturnstruebecause there is room.dropped_is still 0.quote_finishedfirst computes three things outside any guard: the whole milliseconds, the outcome name"ok", and a pointer to theQuote. None of them can throw.- The log step. The lambda calls
log_.write. The broken buffer accepts no characters, so the stream sets its failure flag and, because the test asked it to, throws. The exception leaves the lambda, andguarded’scatch (...)catches it and adds one todropped_, which is now 1. Nothing leavesquote_finished. - The counter step runs anyway, because it has its own guard:
quotes_total{outcome="ok"}becomes 1. - The span step records the
quotespan, withokset totrue. - Back in the service,
quote_finishedreturned normally, soquotereturns theQuoteto its caller as if nothing had happened.
The test then sees what it expects: a successful quote, one dropped
record, the counter at 1, and two spans. If all three steps had shared
one try, the exception from step 3 would have skipped steps 4 and 5.
TelemetryEvents is the only class that knows the event names, metric
names, and span names. Three decisions make it safe:
- Each sink is guarded on its own.
guardedruns one recording step and catches everything it throws. Separate guards mean that a broken log stream does not also lose the counter and the span; onetryaround all three would. - Losses are counted.
catch (...)that silently swallows errors hides problems; here every failed guard incrementsdropped(), which a real service would publish as a metric of its own. A rising dropped count says the telemetry is failing, while the quotes keep working (R3). - Nothing escapes. Every function is
noexcept, as the port requires, and every statement that could throw, including building strings, is inside a guard. What is computed outside the guards cannot throw: a duration conversion, astring_viewthat refers to one ofoutcome_name’s string literals, and a pointer fromstd::get_if.
The mapping from events to records is a policy, and it is all in one place:
| Event | Log line | Metrics | Span |
|---|---|---|---|
carrier_answered |
none (the span has it) | latency histogram | carrier.rates, ok |
carrier_failed |
warn, with the reason |
carrier_errors_total, latency histogram |
carrier.rates, failed |
quote_finished |
info summary, with the price if any |
quotes_total{outcome=...} |
quote, failed only if the carrier was unavailable |
A span is marked failed only when the service could not do its job. “No rate” and an invalid weight are answers: the service worked, and marking them as failures would make error rates mean “customers asked for something we do not offer”.
Step 8: wiring and running it
Section titled “Step 8: wiring and running it”The demo uses three pretend carriers that move a ManualClock
forward, so every duration, and the output, is the same on every run:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Three pretend carriers. Each call moves the clock forward by as long// as the call would take, so the telemetry sees realistic durations.// It shares the demo's ManualClock by reference: the service reads the// same clock before and after the call and sees exactly the step taken.class DemoCarriers final : public shipping::CarrierRates {public: explicit DemoCarriers(ManualClock& clock) noexcept : clock_(clock) {}
// 40ms is a std::chrono literal from std::chrono_literals: a duration // of 40 milliseconds. Prices use integer division, so 1200 / 10 is 120 // and any remainder is dropped. std::optional<long long> rate_cents(const std::string& carrier, int weight_grams) override { if (carrier == "swiftpost") { // fast, and has a rate for every weight clock_.advance(40ms); return 450 + weight_grams / 10; } if (carrier == "parcelco") { // slower, and has no rate above 10 kg clock_.advance(120ms); if (weight_grams > 10'000) return std::nullopt; return 380 + weight_grams / 8; } if (carrier == "slowboat") { // always times out: the expected failure clock_.advance(2000ms); throw CarrierUnavailable("timed out after 2000 ms"); } return std::nullopt; // a carrier nobody has a contract with }
private: ManualClock& clock_;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The composition root: it creates the sinks, the adapter, and the// service, in that order, so each outlives whatever refers to it.// Local objects are destroyed in reverse order at the end of main, so// the service, which holds references to the others, goes first.ManualClock clock;DemoCarriers carriers(clock);shipping::EventLog log(std::cout); // log lines go to standard outputshipping::Metrics metrics;shipping::SpanRecorder spans(100); // keeps at most 100 spans; the demo makes 9shipping::TelemetryEvents telemetry(log, metrics, spans);// The service sees `telemetry` only as a QuoteEvents&: it cannot tell// which adapter it was given.shipping::QuoteService service(carriers, clock, telemetry);The composition root creates the
sinks, then the adapter, then the service. Local objects are destroyed
in reverse order, so the service goes first and the sinks last, and
every reference stays valid while it is used. Swapping ManualClock
for SteadyClock, or TelemetryEvents for NoQuoteEvents, changes
only these lines.
The demo quotes five shipments: a normal one, a weight with no rate, a carrier that times out, a weight of zero, and a request ID that tries to add a fake error line to the log:
-- log --level=info event=quote_finished request_id=r-1001 carrier=swiftpost outcome=ok price_cents=669 took_ms=40level=info event=quote_finished request_id=r-1002 carrier=parcelco outcome=no_rate took_ms=120level=warn event=carrier_failed request_id=r-1003 carrier=slowboat reason="timed out after 2000 ms" took_ms=2000level=info event=quote_finished request_id=r-1003 carrier=slowboat outcome=carrier_unavailable took_ms=2000level=info event=quote_finished request_id=r-1004 carrier=swiftpost outcome=invalid_weight took_ms=0level=info event=quote_finished request_id="r-1005\nlevel=error event=fake" carrier=swiftpost outcome=ok price_cents=599 took_ms=40-- metrics --carrier_errors_total 1quotes_total{outcome="carrier_unavailable"} 1quotes_total{outcome="invalid_weight"} 1quotes_total{outcome="no_rate"} 1quotes_total{outcome="ok"} 2carrier_latency_ms_bucket{le="50"} 2carrier_latency_ms_bucket{le="250"} 3carrier_latency_ms_bucket{le="1000"} 3carrier_latency_ms_bucket{le="+Inf"} 4carrier_latency_ms_count 4carrier_latency_ms_sum 2200-- spans --trace=r-1001 span=carrier.rates parent=quote took_ms=40 ok=truetrace=r-1001 span=quote parent="" took_ms=40 ok=truetrace=r-1002 span=carrier.rates parent=quote took_ms=120 ok=truetrace=r-1002 span=quote parent="" took_ms=120 ok=truetrace=r-1003 span=carrier.rates parent=quote took_ms=2000 ok=falsetrace=r-1003 span=quote parent="" took_ms=2000 ok=falsetrace=r-1004 span=quote parent="" took_ms=0 ok=truetrace="r-1005\nlevel=error event=fake" span=carrier.rates parent=quote took_ms=40 ok=truetrace="r-1005\nlevel=error event=fake" span=quote parent="" took_ms=40 ok=true-- dropped: 0 --Reading it as the people running the service would:
- One line per answer, and a warning for the failure.
r-1003has two lines: the carrier’s failure with its reason, and the summary. Searching forrequest_id=r-1003finds both (R1). - The injection failed. The hostile request ID is written as one
quoted value with
\nin it; there is nolevel=error event=fakeline (R5). - The counters add up. Five requests, five
quotes_total, split by outcome. Four carrier calls, becauser-1004never reached a carrier. - The histogram shows the timeout. Two calls took at most 50 ms,
one at most 250 ms, and one only fits in
+Inf: the 2000 ms timeout. The sum, 2200 ms, says the average carrier call took 550 ms, which no single call did. Averages hide shapes; buckets show them. - The spans show where the time went. For
r-1003, thequotespan took 2000 ms, and all of it was incarrier.rates.
Testing what a component reports
Section titled “Testing what a component reports”What a component reports is behaviour, and it can be tested like any other behaviour. The core’s tests use a fake for the port that records each event as a short line:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A fake for the observability port that remembers each event as one// short line, so a test can check exactly what the core reported.// The lines read like "answered r-1 30ms" or "finished r-1 ok 30ms": the// event, the request ID, then the details, in the order they happened.// This is a fake, not a mock library: a small hand-written class that// implements the port the same way a real adapter would.class RecordingEvents final : public shipping::QuoteEvents {public: void carrier_answered(const QuoteRequest& request, Duration took) noexcept override { add("answered " + request.request_id + ' ' + ms(took)); } void carrier_failed(const QuoteRequest& request, Duration took, std::string_view reason) noexcept override { add("failed " + request.request_id + ' ' + ms(took) + ' ' + std::string(reason)); } void quote_finished(const QuoteRequest& request, const QuoteResult& result, Duration took) noexcept override { add("finished " + request.request_id + ' ' + std::string(shipping::outcome_name(result)) + ' ' + ms(took)); }
std::vector<std::string> lines; // public, so a test can compare it directly
private: // Turns a duration into text such as "30ms", in whole milliseconds. static std::string ms(Duration took) { return std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(took).count()) + "ms"; } // A test fake may terminate on a failed allocation; the real adapter // must not. (If push_back threw inside this noexcept function, the // program would stop at once, which is acceptable in a test.) // The line is taken by value and moved into the vector, not copied. void add(std::string line) noexcept { lines.push_back(std::move(line)); }};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; LLD_CHECK_EQ(actual, expected) does the same// for an equality and prints both values when they differ; and// LLD_CHECK_THROWS(expression, type) fails unless the expression throws// that type of exception. They come from the site's small test header,// lld_test.hpp.//// Each test starts with a Fixture, defined earlier in this file: a// ManualClock at 0, a ScriptedCarrier that by default answers 500 cents// after advancing the clock 30 ms, a RecordingEvents, and a QuoteService// wired to all three. A test changes the carrier's settings first if it// needs another answer.
// Sets up: the default carrier (500 cents, 30 ms). Proves: the price is// 500 + the 99 cent fee = 599, and the core reported two events, the// carrier's answer and then the summary, each with the exact 30 ms.LLD_TEST(a_quote_adds_the_fee_and_reports_the_carrier_call_and_the_result) { Fixture f; // The braces build a QuoteRequest: request_id, carrier, weight_grams. const QuoteResult result = f.service.quote({"r-1", "swiftpost", 1000}); LLD_CHECK(std::holds_alternative<Quote>(result)); LLD_CHECK_EQ(std::get<Quote>(result).price_cents, 599); // Comparing two vectors checks every line and their order. The extra // parentheses keep the braces' commas from confusing the macro. LLD_CHECK(f.events.lines == (std::vector<std::string>{"answered r-1 30ms", "finished r-1 ok 30ms"}));}
// Sets up: a carrier that throws CarrierUnavailable after 2000 ms.// Proves: the result is carrier_unavailable, the failure is reported with// its reason and duration, and the summary still follows.LLD_TEST(a_failed_carrier_is_reported_with_its_reason_then_the_result) { Fixture f; f.carrier.fails = true; f.carrier.delay = 2000ms; const QuoteResult result = f.service.quote({"r-2", "slowboat", 1000}); LLD_CHECK(std::get<QuoteFailure>(result) == QuoteFailure::carrier_unavailable); LLD_CHECK(f.events.lines == (std::vector<std::string>{"failed r-2 2000ms connection refused", "finished r-2 carrier_unavailable 2000ms"}));}
// Sets up: a carrier that answers with no rate. Proves: that is reported// as "answered", not "failed", and the result is no_rate.LLD_TEST(no_rate_counts_as_an_answer_from_the_carrier) { Fixture f; f.carrier.rate = std::nullopt; const QuoteResult result = f.service.quote({"r-3", "parcelco", 1000}); LLD_CHECK(std::get<QuoteFailure>(result) == QuoteFailure::no_rate); LLD_CHECK(f.events.lines == (std::vector<std::string>{"answered r-3 30ms", "finished r-3 no_rate 30ms"}));}
// Sets up: weights just outside the valid range, 0 and 30001, then the// largest valid one, 30000. Proves: the invalid ones never call the// carrier (calls stays 0, and no time passes) but still get a summary// event, and the limit itself is accepted.LLD_TEST(an_invalid_weight_never_reaches_the_carrier_but_is_still_reported) { Fixture f; // static_cast<void>(...) says the result is ignored on purpose: these // two calls are made only for the events they report. static_cast<void>(f.service.quote({"r-4", "swiftpost", 0})); static_cast<void>(f.service.quote({"r-5", "swiftpost", QuoteService::max_weight_grams + 1})); LLD_CHECK_EQ(f.carrier.calls, 0); LLD_CHECK(f.events.lines == (std::vector<std::string>{"finished r-4 invalid_weight 0ms", "finished r-5 invalid_weight 0ms"})); const QuoteResult heaviest = f.service.quote({"r-6", "swiftpost", QuoteService::max_weight_grams}); LLD_CHECK(std::holds_alternative<Quote>(heaviest));}
// Sets up: a carrier that throws std::logic_error, standing for a bug.// Proves: the exception reaches the caller unchanged, and no event at all// was reported, not even carrier_failed.LLD_TEST(an_unexpected_exception_reaches_the_caller_without_a_finished_event) { Fixture f; f.carrier.breaks = true; LLD_CHECK_THROWS(f.service.quote({"r-7", "swiftpost", 1000}), std::logic_error); LLD_CHECK(f.events.lines.empty());}The manual clock makes the durations exact, so “the carrier failure is reported with 2000 ms” is an ordinary equality. None of these tests knows the log format or a metric name: changing the format cannot break them, and they check what the core promised (R4).
The adapters have their own tests, for the format and for failure:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Proves each rule of log_value with one small value. Reading the// expected strings: in C++ source, \" is one quote character and \\ is// one backslash, so "\"\"" is the two characters "" (an empty value,// quoted).LLD_TEST(plain_values_are_written_as_they_are_and_others_are_quoted) { LLD_CHECK_EQ(log_value("r-1001"), "r-1001"); // only plain characters: unchanged LLD_CHECK_EQ(log_value(""), "\"\""); LLD_CHECK_EQ(log_value("timed out"), "\"timed out\""); // a space needs quotes // The value say "hi" \o/ becomes "say \"hi\" \\o/": quotes and the // backslash each get a backslash in front. LLD_CHECK_EQ(log_value("say \"hi\" \\o/"), "\"say \\\"hi\\\" \\\\o/\""); // A real newline, carriage return, and tab become visible pairs. LLD_CHECK_EQ(log_value("a\nb\rc\td"), "\"a\\nb\\rc\\td\""); // The bell character, byte 7. The length 5 is given so the string is // built from exactly those five characters. LLD_CHECK_EQ(log_value(std::string("bell\x07", 5)), "\"bell\\x07\"");}
// Sets up: a log that writes into a string (std::ostringstream) instead// of the screen, and a request ID that contains a newline and a fake// second record. Proves: the output is exactly one line, with the hostile// text kept inside one quoted value.LLD_TEST(a_hostile_value_cannot_start_a_line_of_its_own) { std::ostringstream out; EventLog log(out); log.write("info", "quote_finished", {{"request_id", "r-1\nlevel=error event=fake"}}); LLD_CHECK_EQ(out.str(), "level=info event=quote_finished request_id=\"r-1\\nlevel=error event=fake\"\n"); LLD_CHECK_EQ(count_lines(out.str()), 1); // count_lines counts the '\n' characters}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Sets up: the real adapter and sinks, but the log writes to BrokenBuf,// defined earlier in this file, a stream buffer that fails every write.// The carrier is FixedCarrier, which always answers 500 cents.// Proves: the quote still succeeds, and of the five recording steps the// adapter runs for it (latency, carrier span, summary log line, outcome// counter, quote span) only the log line is lost, and it is counted.LLD_TEST(a_broken_log_costs_one_record_and_never_the_quote) { BrokenBuf broken; std::ostream out(&broken); // a stream that sends its characters to `broken` out.exceptions(std::ios_base::badbit); // the stream throws when a write fails EventLog log(out); Metrics metrics; SpanRecorder spans(10); TelemetryEvents telemetry(log, metrics, spans); shipping::ManualClock clock; FixedCarrier carrier; QuoteService service(carrier, clock, telemetry);
LLD_CHECK(std::holds_alternative<Quote>(service.quote({"r-1", "swiftpost", 1000}))); LLD_CHECK_EQ(telemetry.dropped(), 1); // the summary line LLD_CHECK_EQ(metrics.counter("quotes_total{outcome=\"ok\"}"), 1); LLD_CHECK_EQ(spans.spans().size(), std::size_t{2}); // carrier.rates and quote}
// Sets up: a span recorder with room for one span. Proves: the first// span, carrier.rates, is kept; the second, quote, is refused (record// returns false) and counted as dropped; the log is not affected.LLD_TEST(a_full_span_recorder_drops_spans_and_counts_them) { std::ostringstream out; EventLog log(out); Metrics metrics; SpanRecorder spans(1); TelemetryEvents telemetry(log, metrics, spans); shipping::ManualClock clock; FixedCarrier carrier; QuoteService service(carrier, clock, telemetry);
static_cast<void>(service.quote({"r-1", "swiftpost", 1000})); LLD_CHECK_EQ(telemetry.dropped(), 1); // the "quote" span; "carrier.rates" was kept const std::vector<shipping::Span> kept = spans.spans(); LLD_CHECK_EQ(kept.size(), std::size_t{1}); LLD_CHECK_EQ(kept.at(0).name, "carrier.rates"); // One line: carrier_answered writes none, quote_finished writes one. LLD_CHECK_EQ(count_lines(out.str()), 1);}BrokenBuf is a stream buffer whose every write fails, like a full
disk, and the stream is set to throw. The test checks the promise of
R3 from the outside: the quote still succeeds, the counter and both
spans are still recorded, and exactly one record, the log line, is
counted as lost.
Finally, a concurrency test runs four threads with the real clock:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Sets up: one service, one adapter, and one set of sinks shared by four// threads, each making 250 quotes with the real clock. Proves: every// count is exact, 1000 quotes, 1000 latencies, 2000 spans, 1000 lines,// and nothing dropped. A lost update or a lost line would show up as a// wrong count. Two lines mixed together would not: they still hold two// newlines. The lock in EventLog::write is what prevents that.LLD_TEST(four_threads_quoting_at_once_lose_nothing) { constexpr int threads = 4; constexpr int quotes_each = 250; std::ostringstream out; EventLog log(out); Metrics metrics; SpanRecorder spans(2 * threads * quotes_each); // two spans per quote: room for all TelemetryEvents telemetry(log, metrics, spans); shipping::SteadyClock clock; FixedCarrier carrier; // keeps no state, so it may be shared QuoteService service(carrier, clock, telemetry); { // std::jthread starts a thread at once and, unlike std::thread, // joins it (waits for it to finish) when it is destroyed. std::vector<std::jthread> workers; for (int t = 0; t < threads; ++t) { // emplace_back builds the jthread in the vector, running this // lambda on a new thread. The lambda captures the service by // reference, since all threads share it, and the thread number // `t` by value, since `t` changes as the loop goes on. // quotes_each needs no capture: it is a constexpr constant. workers.emplace_back([&service, t] { for (int i = 0; i < quotes_each; ++i) { // A unique ID per quote, such as r-2-17. const std::string id = "r-" + std::to_string(t) + '-' + std::to_string(i); static_cast<void>(service.quote({id, "swiftpost", 1000})); } }); } } // every worker is joined here: `workers` is destroyed, so the checks below see all work LLD_CHECK_EQ(metrics.counter("quotes_total{outcome=\"ok\"}"), threads * quotes_each); LLD_CHECK_EQ(metrics.latency_count(), threads * quotes_each); LLD_CHECK_EQ(spans.spans().size(), std::size_t{2 * threads * quotes_each}); LLD_CHECK_EQ(count_lines(out.str()), threads * quotes_each); LLD_CHECK_EQ(telemetry.dropped(), 0);}Every count must come out exact: no lost increments, no lost or merged lines. The test also runs in the ThreadSanitizer build, which reports data races that a passing count could hide. It passed in all four builds, including that one.
Other ways to add observability
Section titled “Other ways to add observability”| Approach | Good for | Falls short when |
|---|---|---|
| An events port in the core’s words (this page) | Cores with business outcomes worth reporting | The events are few and the format will never change; then it is ceremony |
A Decorator around a port, such as a timing CarrierRates |
Timing and counting calls without touching the core at all | It sees each call’s arguments, its return value, and its exceptions, but not the request’s result: not the requests that never reach the carrier, such as an invalid weight, nor the fee, nor the final outcome |
A logger interface passed to the core, log(level, text) |
Programs whose logs are their main output | The core still chooses messages and levels, so tests still parse text and metrics still need a second seam |
| A global logger or a Singleton | Small programs and scripts | Tests share it, it hides a dependency, and it cannot differ between two services in one process |
| Several observers of one port (Observer) | Many independent listeners, added at run time | One fixed set of sinks is simpler as one adapter that fans out, as TelemetryEvents does |
These combine. A timing decorator on the carrier port is a fine way to add carrier metrics to a core that cannot be changed; the events port is better when the interesting facts are outcomes only the core knows. The two can live in one program.
Every event is a virtual call, and the adapter builds strings, takes a lock for each sink call, and writes a line. That is small next to a network call to a carrier, which is what this service does for most requests. It is not small inside a loop that runs millions of times a second; there, record counts in local variables and report them once, or sample. No performance numbers were measured for this page; profile before deciding, as Performance: allocation, locality, and data layout explains.
The other cost is design effort: a port, a fake, and an adapter
instead of one line of std::clog. For a small command-line tool that
prints its progress to the terminal, that line is the right answer.
class shipping::QuoteEvents
port owned by the core; every function noexcept
Member functions
virtual void carrier_answered(const QuoteRequest& request, Duration took) noexcept = 0;virtual void carrier_failed(const QuoteRequest& request, Duration took, std::string_view reason) noexcept = 0;virtual void quote_finished(const QuoteRequest& request, const QuoteResult& result, Duration took) noexcept = 0;
class shipping::TelemetryEvents
final; borrows its three sinks
Data members
EventLog& log_;Metrics& metrics_;SpanRecorder& spans_;std::atomic<long long> dropped_;
Member functions
TelemetryEvents(EventLog& log, Metrics& metrics, SpanRecorder& spans) noexcept;long long dropped() const noexcept;records lost to a failed or full sink
class shipping::QuoteService
keeps no state of its own
Data members
CarrierRates& rates_;const Clock& clock_;QuoteEvents& events_;
Member functions
QuoteService(CarrierRates& rates, const Clock& clock, QuoteEvents& events) noexcept;QuoteResult quote(const QuoteRequest& request);exactly one quote_finished per answer
Common mistakes
Section titled “Common mistakes”- Formatting log text in the core. The format becomes an interface that tests and alerts depend on, and changing the logging library means editing business code.
- Using input as a metric label. Request IDs, user names, and anything a caller can choose make the metric grow without limit.
- Writing caller-supplied text into logs unescaped. It lets callers forge records, and can break whatever parses the log.
- Letting telemetry fail the request. A full disk should cost log
lines, not customers. Make the port
noexceptand guard the adapter. - Swallowing telemetry failures silently. Count them, or nobody will know the logs stopped.
- Timing with the system clock. It can jump; use
std::chrono::steady_clock, and take the clock as a dependency so tests can control it. - Logging secrets or personal data. Logs are copied and kept; keep such data out of them from the start.
- Measuring only successes. Timeouts are the slowest calls; leaving them out makes latency look best when it is worst.
When the requirements change
Section titled “When the requirements change”- “Add a metric for the new rate cache.” Give the cache its own
small port in its own words, as the exercise below does, rather than
passing
Metricsinto it. - “Count quotes per carrier.” Only after the carrier name is
checked against the configured carriers; map anything else to a
single
othervalue, so the label stays a closed set. - “Send traces to a real tracing system.” Write a new adapter, or
replace
SpanRecorderbehindTelemetryEvents; the core does not change. Propagating the trace ID to carriers also needs theCarrierRatesport to carry it, which is a change to the core’s port, and worth making on purpose. - “Some requests contain card numbers.” Decide which fields may be logged at all, and enforce it in the adapter. Escaping stops forged lines, not leaked data. Security-sensitive boundaries covers validating input at the edge.
- “Logging is slowing us down.” First measure. Then move writing to a background thread with a bounded queue, sample traces, or drop the lowest-value lines.
Exercise
Section titled “Exercise”Exercise: Add a metric seam
The team puts a cache in front of the carrier rate systems, so that the same carrier and weight are not asked twice. Operators want to see how often the cache helps.
- Where does the hit-or-miss fact come from, and how should it reach
Metrics? Sketch the classes. - A colleague suggests passing
Metrics&straight into the cache and callingmetrics.add("rate_cache_hits"). What does that cost? - Which label, if any, should the cache counter have?
- For each question, choose a log, a metric, or a trace: (a) “How
many carrier calls took longer than a second today?” (b) “Which carrier
names did callers send that we do not know?” (c) “Why did request
r-2040take three seconds?”
Show the explained answer
-
Only the cache knows whether it hit, so it reports the fact through a port of its own, in its own words, and an adapter turns that into counters. The cache is a Decorator of
CarrierRates, so the core does not change. This sketch was compiled with both compilers in a scratch file, together with the example’s headers; it was not run.class RateCacheEvents {public:virtual ~RateCacheEvents() = default;virtual void cache_hit() noexcept = 0;virtual void cache_miss() noexcept = 0;};// The cache: a decorator that reports what it did, in its own words.class CachingRates final : public CarrierRates {public:CachingRates(CarrierRates& inner, RateCacheEvents& events) noexcept: inner_(inner), events_(events) {}std::optional<long long> rate_cents(const std::string& carrier, int weight_grams) override {const std::pair<std::string, int> key(carrier, weight_grams);bool hit = false;std::optional<long long> rate;{const std::scoped_lock lock(mutex_);if (const auto found = cache_.find(key); found != cache_.end()) {hit = true;rate = found->second;}}if (hit) {events_.cache_hit(); // reported after the lock is releasedreturn rate;}events_.cache_miss();rate = inner_.rate_cents(carrier, weight_grams);const std::scoped_lock lock(mutex_);cache_.insert_or_assign(key, rate);return rate;}private:CarrierRates& inner_;RateCacheEvents& events_;std::mutex mutex_;std::map<std::pair<std::string, int>, std::optional<long long>> cache_;};// The adapter: the only code that knows the metric names.class CacheMetrics final : public RateCacheEvents {public:explicit CacheMetrics(Metrics& metrics) noexcept : metrics_(metrics) {}void cache_hit() noexcept override { count("hit"); }void cache_miss() noexcept override { count("miss"); }private:void count(std::string_view result) noexcept {try {metrics_.add("rate_cache_total{result=\"" + std::string(result) + "\"}");} catch (...) {// Lost; a real adapter would count it, as TelemetryEvents does.}}Metrics& metrics_;};The lock is released during the carrier call, so two threads that miss on the same key at once may both ask the carrier; for a price list, that is acceptable. A failed carrier call throws past the cache and is not stored. A real cache would also need a size limit and an expiry time, as Cache policies and invalidation explains. Tests give
CachingRatesa recording fake ofRateCacheEvents, as the core’s tests do forQuoteEvents. -
The cache would then know the metric’s name and the
Metricsclass, so its tests must read counters by name, renaming the metric means editing the cache, and moving to another metrics system means editing every class that counts. Nothing would stop the cache from throwing out of a counter either. It is the same coupling as Step 1, with a counter in place of a log line. -
result="hit"orresult="miss": a closed set of two values, so the hit ratio is one division. Not the carrier, for the reason in Step 5, unless the names are first checked against the configured carriers; and never the weight, which has thousands of values. -
(a) A metric: the latency histogram’s
+Infcount minus itsle="1000"bucket gives the answer cheaply, without reading any log. The same question about whole quotes needs a second histogram, fed fromquote_finished: carrier calls and quotes are different counts, since an invalid weight or a cache hit makes no carrier call. (b) A log: a warning with the unknown name in a field. As a metric label, the names themselves would be unbounded. (c) A trace, to see which step took the time, and then the request’s log lines for the details, found by its request ID.
Summary
Section titled “Summary”- Logs say what happened to one request; metrics count and time everything cheaply; traces show where one request spent its time. Each is cheap for its own questions.
- Give the core an observability port with events in its own words. Formats, metric names, and tracing systems then belong to adapters, and the core’s tests check events, not text.
- Make the port
noexcept, and guard every sink in the adapter, so recording can lose data but never a request. Count what is lost. - Escape every value that reaches a log line, and label metrics only with values from closed sets.
- Take time from a
Clockport, backed bysteady_clock, so that durations can be tested exactly. - For a small tool, a line of output is enough; this structure pays when a service runs unattended and many people need to understand it.