How would you lead a C++ codebase's move of its logging and console output from iostreams and printf to std::format?
answer
- toolchain floor before syntax
- one checked wrapper at the boundary
- output text will change
- runtime templates and exceptions
- convert by module, measure
basics
~20 sFirst confirm every supported compiler ships C++20 <format>. Route all output through a wrapper taking std::format_string so call sites stay compile-time checked, plan for changed number text, handle runtime templates and exceptions, and convert module by module behind tests.
solid answer
~50 sI would start with the toolchain: `std::format` needs C++20 and a library with `<format>` (GCC 13.1's libstdc++, for example), and `std::print` needs C++23, so the oldest compiler we ship with sets the floor. Then I would add one logging entry point, `template<class... Args> void log(std::format_string<Args...>, Args&&...)`, so every call site keeps the compile-time check, and convert modules behind it rather than editing every line at once. I would warn downstream consumers that output text changes: `{}` prints a `double` as its shortest round-trip form, not iostreams' six significant digits, and `std::format` ignores the locale unless `L` is used. Types with only `operator<<` need formatters. Runtime templates move to `std::vformat` with `std::format_error` caught, because a throwing log call must not crash the process. I would measure compile time, binary size and hot-path cost before and after.
code
cpp · 22 lines#include <cstdio>
#include <format>
#include <iostream>
#include <string>
#include <utility>
template <class... Args>
void log_info(std::format_string<Args...> fmt, Args&&... args) {
std::string line = std::format(fmt, std::forward<Args>(args)...);
std::fputs(line.c_str(), stderr);
std::fputc('\n', stderr);
}
int main() {
double latency = 0.1 + 0.2;
std::cout << "iostream: " << latency << '\n';
std::printf("printf %%g: %g\n", latency);
std::cout << std::format("format {{}}: {}", latency) << '\n';
std::cout << std::format("format {{:.3f}}: {:.3f}", latency) << '\n';
log_info("tick {} took {:.1f} ms", 42, 16.67);
// log_info("tick {:d}", "oops"); // rejected at compile time
}go deeper
Recall that std::format needs C++20, std::print needs C++23, and that a type needs a formatter to be printed with std::format.
Explain why a wrapper taking std::format_string keeps compile-time checks, and why doubles print differently from iostreams.
Show how to convert safely: golden tests, formatters for logged types, vformat for runtime templates, and exception handling in the log path.
Own the tradeoff: toolchain floor, downstream log consumers, compile time and hot-path cost, rollout order, and the trigger for postponing.
## The decision in front of a lead Moving logging and console output to `std::format` is not a search-and-replace. It changes the toolchain floor, the text that downstream tools parse, the failure mode of bad format strings, and the cost of a log line. A lead has to decide whether the safety is worth those costs, and then how to get there without a flag day. ## Step 1: the toolchain floor - `std::format` needs **C++20** and a standard library that ships `<format>`: libstdc++ lists text formatting as complete from **GCC 13.1**, and libc++ from LLVM 14. - `std::print` and `std::println` need **C++23**: GCC 14.1, LLVM 18. - The oldest compiler on the support matrix decides. A game console SDK, an embedded vendor compiler or a long-term-support Linux distribution often holds the line, and that is the first conversation, before any code changes. If the floor is C++20, use `std::format` plus your own sink. If it is C++23 everywhere, `std::print` can write to C streams directly. ## Step 2: one checked boundary Do not let thousands of call sites call `std::format` directly with ad hoc sinks. Introduce one entry point that keeps the compile-time check: ```cpp template <class... Args> void log_info(std::format_string<Args...> fmt, Args&&... args); ``` Because the parameter is `std::format_string<Args...>`, every call such as `log_info("tick {} took {:.1f} ms", tick, ms)` is checked where it is written, and the wrapper owns the sink, the timestamp, the level and the locking. Old macros can forward to it during the transition. ## Step 3: plan for output that changes Teams underestimate this part. Dashboards, alert rules and tests that compare log text will notice: | Value | `std::cout <<` | `printf("%g")` | `std::format("{}")` | |---|---|---|---| | `0.1 + 0.2` | `0.3` | `0.3` | `0.30000000000000004` | | `true` | `1` | not applicable | `true` | | `1234567` with a grouping locale imbued | grouped | ungrouped | ungrouped unless `{:L}` | 1. Decide on an explicit precision for floating-point fields that humans read, such as `{:.3f}`, instead of relying on defaults. 2. Announce the change to whoever parses the logs, and update golden-output tests in the same change as the conversion. 3. Treat locale as a decision: `std::format` is locale-independent by default, which is usually what machine-read logs want. ## Step 4: the things that do not convert mechanically - **Types with only `operator<<`.** `std::format` never calls streams, so each type that appears in logs needs a `std::formatter` specialization. Prioritise by how often the type is logged. - **Runtime templates.** Translation tables and configurable messages cannot pass the consteval check. They go through `std::vformat`, which throws `std::format_error` on a bad template, so validate them when they are loaded. - **Exceptions in log paths.** A failed write in `std::print` throws `std::system_error`; a bad runtime template throws `std::format_error`. Logging must not take the process down, so the wrapper catches and degrades to a raw line. - **Mixed output during the transition.** `std::print` writes to the C `stdout`. If the code base ever called `std::ios::sync_with_stdio(false)`, interleaving with `std::cout` breaks, so either convert a binary's console output in one go or leave synchronisation on. ## Step 5: measure, then roll out - **Compile time and binary size.** Every distinct argument-type list instantiates formatting code. Measure a representative target before and after rather than assuming either way. - **Hot paths.** `std::format` returns a new `std::string`. In a per-frame or per-packet path, `std::format_to` into a reused buffer avoids the allocation; benchmark the path you care about. - **Order of conversion.** Convert the wrapper first, then one module at a time, with code review rejecting new `printf` and `std::cout` logging in converted modules. A static-analysis or lint rule in CI keeps it from regressing. ## When not to do it If the oldest supported compiler lacks `<format>`, if the logs feed a parser that cannot be changed this quarter, or if the existing code already uses a checked formatting layer, the migration may cost more than it saves. Saying "not yet, and here is the trigger that would change my mind" is a legitimate principal answer. ## What the team gets in return The payoff is real and worth stating to whoever funds the work: a whole class of crash, the mismatched `printf` argument, becomes a compile error; log calls read as one template instead of a chain of `<<` and manipulators; formatting state no longer leaks between lines; and user types gain one formatting definition that both console output and logs share.
- How do you stop new printf or std::cout logging from creeping back into converted modules?Make the wrapper the only sanctioned path and enforce it mechanically: a lint rule or static-analysis check in CI that flags `printf`, `fprintf` and `std::cout <<` in converted directories, plus a review checklist. Keep an allow-list for genuine console tools, and remove directories from the exception list as they convert.
- What would make you postpone the migration?A supported compiler without `<format>`, log consumers that cannot absorb changed number text yet, or a hot path where measured formatting cost regresses. I would write down the trigger, such as dropping the oldest compiler, and revisit then, rather than half-converting and maintaining two styles indefinitely.
- A regex rewrite of printf calls to std::format finishes the migration
- std::format prints doubles exactly as std::cout does, so log parsers are unaffected
- Types with operator<< print through std::format automatically
- Runtime-loaded templates can be passed straight to std::format
- std::print is available wherever std::format is
Assumes C++20 std::format and C++23 std::print; library support versions are from the libstdc++ and libc++ status pages.