spdlog for C++
spdlog is a C++ logging library with {fmt}-style formatting, named loggers,
runtime log levels, multiple output sinks, rotating files, and synchronous or
asynchronous operation. This tutorial starts with a minimal Ubuntu 24.04
program, then builds a synchronous component logger controlled by environment
variables and a separate CSV telemetry writer.
Install on Ubuntu 24.04
Ubuntu 24.04 supplies spdlog 1.12.0 and its {fmt} dependency. Confirm the
installed version with:
The examples use only the Ubuntu package. No manual installation is required.
The four concepts to know
- A log record is one event: level, time, logger name, and message.
- A logger receives records from one application component, such as
cameraornetwork. - A sink sends records to a destination, such as the console or a file.
- A pattern controls how a sink converts each record to text.
One logger can share several sinks:
flowchart LR
C[camera logger] --> O[colored console sink]
C --> F[rotating file sink]
N[network logger] --> O
N --> F
T[telemetry logger] --> CSV[CSV file sink]
The diagnostic log explains what the program is doing. Telemetry stores fixed-schema measurements for analysis. They are related, but they are not the same data product.
Minimal CMake example
| main.cpp | |
|---|---|
| CMakeLists.txt | |
|---|---|
Build and run from the downloaded example directory:
color section
%^ and %$ mark the colored portion of the console pattern. They have an
effect only when the sink supports colors.
Log levels
From most detailed to most severe, spdlog levels are:
| Level | Typical use |
|---|---|
trace |
Very detailed execution flow. |
debug |
Values useful while developing or diagnosing. |
info |
Normal lifecycle events. |
warn |
Unexpected condition from which the program can recover. |
error |
An operation failed. |
critical |
The process or an essential subsystem cannot continue safely. |
off |
Disable the logger. |
A logger emits a record only when its level is at least as severe as its
configured threshold. With an info threshold, trace and debug records are
filtered out.
Runtime and compile-time filtering differ
The examples call logger methods such as camera->debug(...), which remain
available for runtime filtering. Projects using macros such as
SPDLOG_DEBUG must also set SPDLOG_ACTIVE_LEVEL at compile time if they
want lower-level macro calls compiled into the binary.
Console and rotating-file sinks
The configured example creates one colored console sink and one rotating-file sink. All three component loggers share them:
The file rotates after 5 MiB and retains three older files:
Rotation limits storage growth. It does not archive logs permanently; the oldest rotated file is deleted.
Control levels from the environment
The configured program calls:
Set one global level:
Set a global level and override individual components:
This configuration means:
cameraemitsdebugand more severe records;networkstarts atwarn;controlemits nothing;- every other diagnostic logger uses
info.
Unlisted components inherit the global level
In SPDLOG_LEVEL="info,camera=debug", network and control inherit
info. A component is disabled only when it is explicitly assigned off
or the global level is off.
The example validates configuration before passing it to spdlog. Unknown components, duplicate entries, empty tokens, and invalid levels stop startup:
This validation matters because spdlog's native environment parser ignores unrecognized levels instead of reporting them as errors.
Control formatting per sink
The console should be compact and easy to scan. The file should preserve more context. The program therefore reads two environment variables:
Common flags are:
| Flag | Meaning |
|---|---|
%Y-%m-%d |
Date. |
%H:%M:%S |
Time. |
%e |
Milliseconds. |
%l |
Log level. |
%n |
Logger or component name. |
%t |
Thread ID. |
%v |
User message. |
%^ ... %$ |
Start and end console color range. |
If a variable is unset, the application uses the pattern shown above as its
default. If a supplied pattern is invalid, set_pattern throws and the program
exits with a configuration error.
Complete configured example
Download main.cpp and
CMakeLists.txt.
| CMakeLists.txt | |
|---|---|
| main.cpp | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 | |
Build and run:
The example is synchronous: the calling thread formats each accepted record and writes it to its sinks before returning.
Use spdlog for CSV telemetry
spdlog can write CSV lines, but it is not a CSV database or schema library. The application owns:
- the filename and schema;
- the header and column order;
- value formatting and units;
- quoting and escaping;
- flushing and retention.
The configured example creates one file per run:
It uses a dedicated file-only logger whose pattern is %v, so spdlog does not
add a level or logger name around the CSV row:
The sequence column helps detect missing samples. The component column records which subsystem produced the measurement.
CSV strings must be escaped
The example uses a fixed component name and numeric values, none of which
contains commas, quotes, or newlines. General text fields require correct
CSV quoting. A pattern such as "{},{},{}" does not escape arbitrary input
safely.
The telemetry logger is intentionally separate from the registered diagnostic
loggers, so SPDLOG_LEVEL cannot accidentally disable measurement collection.
It writes the header once, appends data rows, and flushes before shutdown.
Synchronous versus asynchronous logging
Synchronous flow:
Asynchronous flow:
Asynchronous pros
- Reduces time spent doing file I/O on application threads.
- Can reduce latency spikes when the disk is temporarily slow.
- Helps applications producing many diagnostic records from several threads.
Asynchronous cons
- Requires a thread pool, bounded queue, overflow policy, and careful shutdown.
- Queued records may be lost if the process crashes.
- Background errors are harder to report to the application.
- Queueing adds overhead and may not help at low log rates.
- More than one worker can complicate ordering.
When the queue is full, a blocking policy preserves records but can stall the
producer. overrun_oldest keeps the producer moving by discarding older
records.
Do not silently discard required telemetry
overrun_oldest may be acceptable for verbose diagnostic messages. It is a
dangerous default for CSV telemetry because missing rows can invalidate
analysis. Keep telemetry synchronous or use a blocking queue when every
sample matters.
Start with synchronous logging. Move diagnostics to async only after measuring
a real logging bottleneck. Always flush important loggers and call
spdlog::shutdown() during normal application exit.
Optional FetchContent setup
Ubuntu packages are the supported path for these examples. A project that must
pin and build another spdlog release can use CMake FetchContent instead:
Pin a tag rather than following a moving branch. Do not combine the Ubuntu spdlog target and a fetched spdlog target in the same executable.