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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
// SPDX-FileCopyrightText: (c) 2026 Joel Winarske
// SPDX-License-Identifier: MIT
//! drmkit's library-wide diagnostic surface.
//!
//! Port of `src/log.hpp` from drm-cxx @ `dc2915b`. Two knobs are exposed,
//! matching the C++ contract:
//!
//! 1. [`set_log_level`] — process-wide threshold. Records at or below the
//! active level are emitted; the rest are dropped *before* formatting cost
//! is paid. A call below the threshold reduces to one relaxed atomic load
//! and a branch.
//!
//! 2. [`set_log_sink`] — process-wide redirection hook. The default sink
//! writes to stderr (errors, warnings) or stdout (info, debug) prefixed
//! with `[drm:LEVEL] `. Consumers can forward to `tracing`, journald,
//! syslog, or an in-memory test buffer. [`reset_log_sink`] restores the
//! default — the Rust spelling of the C++ `set_log_sink(nullptr)` path.
//!
//! # Deviations from the C++ original
//!
//! The C++ `set_log_sink` is documented thread-unsafe ("install once during
//! application startup, before spinning up worker threads"), and its
//! `set_log_level` is a plain unsynchronized write. Here both are genuinely
//! thread-safe: the level is an [`AtomicU8`] and the sink lives behind an
//! [`RwLock`] whose guard is released before the sink runs, so a sink that logs
//! cannot deadlock and a sink that panics cannot wedge logging for the rest of
//! the process. The startup-only discipline remains good practice; it is no
//! longer load-bearing.
//!
//! # Untrusted content in log records
//!
//! Records are delivered to the sink verbatim — no escaping, no newline
//! stripping. That matters here more than in a typical library, because some
//! of what drmkit will log is attacker-influenced: EDID monitor names and
//! serial strings come off the wire from whatever display is plugged in, and
//! a hostile or simply malformed EDID can carry newlines or ANSI escape
//! sequences. Written straight to a terminal by the built-in sink, those can
//! forge log lines or move the cursor.
//!
//! The C++ original has the same property. Rather than diverge silently, the
//! rule for the port is: **sanitize at the point the untrusted string enters a
//! record, not in the sink.** Any crate that logs an EDID string must sanitize
//! it before formatting -- none currently logs one -- because the sink cannot
//! tell a monitor name from a driver name once they are one formatted string.
//! Consumers who route this into a terminal and cannot trust their displays
//! should install a sink that escapes control characters.
//!
//! # Initial level
//!
//! The C++ side bakes its default in at compile time via `DRM_CXX_LOG_LEVEL`.
//! Here the initial level resolves once, on first use, from the
//! `DRMKIT_LOG_LEVEL` environment variable (`silent`/`error`/`warn`/`info`/
//! `debug`, case-insensitive, or the numeric discriminant, plus the aliases
//! `off`/`none`, `warning` and `trace`). An unset or unparseable value yields
//! [`LogLevel::Info`], matching the C++ default. An explicit [`set_log_level`]
//! before first use always wins.
//!
//! # Example
//!
//! ```
//! use drmkit_log::{LogLevel, log_warn, set_log_level};
//!
//! set_log_level(LogLevel::Warn);
//! log_warn!("plane {} rejected modifier {:#x}", 31, 0x0100_0000_0000_0001_u64);
//! ```
//!
//! # A note on the examples
//!
//! The level and the sink are process-global, and under edition 2024 every
//! doctest in a crate is merged into one binary and run on parallel threads.
//! Examples here therefore *demonstrate* the API but never assert on what a
//! sink received: a concurrently running example would have replaced the sink
//! or moved the threshold, and the assertion would fail for reasons having
//! nothing to do with the code. The behavioral assertions live in the unit
//! tests, which serialize on a mutex the way the C++ gtest fixture does.
use fmt;
use Write as _;
use ;
use ;
pub use install_tracing_sink;
/// Severity of a diagnostic record.
///
/// Discriminants match the C++ `drm::LogLevel` byte-for-byte, so a consumer
/// bridging both libraries can cast between them. Ordering is by verbosity:
/// a record is admitted when the active level is `>=` the record's level, so
/// [`LogLevel::Silent`] admits nothing and [`LogLevel::Debug`] admits all.
/// A sink receives the record's level and its fully formatted body — no level
/// prefix, no trailing newline.
///
/// Sinks are invoked synchronously on the calling thread; a sink needing async
/// dispatch or extra buffering arranges it internally. A sink must tolerate
/// being called from any thread, and must not assume it is the only sink the
/// process will ever install.
pub type LogSink = ;
/// Sentinel meaning "initial level not yet resolved from the environment".
/// Distinct from every real discriminant (0..=4).
const LEVEL_UNRESOLVED: u8 = u8MAX;
static LEVEL: AtomicU8 = new;
/// The active process-wide threshold.
///
/// On the first call — and only then — an unset level resolves from
/// `DRMKIT_LOG_LEVEL`, defaulting to [`LogLevel::Info`].
/// Map a stored byte back to a level. Only ever called with a byte this module
/// wrote, so the fallback is unreachable in practice — but it stays total
/// rather than panicking inside the logger.
/// Set the process-wide threshold.
/// Install a sink, replacing whatever was there.
///
/// The previous sink is dropped once the last in-flight emit using it returns.
///
/// ```
/// use std::sync::{Arc, Mutex};
/// use drmkit_log::{LogLevel, log_error, set_log_level, set_log_sink};
///
/// let captured: Arc<Mutex<Vec<(LogLevel, String)>>> = Arc::new(Mutex::new(Vec::new()));
/// let sink_target = Arc::clone(&captured);
/// set_log_sink(move |level, message| {
/// sink_target.lock().unwrap().push((level, message.to_owned()));
/// });
/// set_log_level(LogLevel::Debug);
///
/// log_error!("answer is {}", 42);
/// // Not asserted on here: the sink is process-global and a concurrently
/// // running example may have replaced it. See "A note on the examples".
/// ```
/// Restore the built-in stdio sink — the Rust spelling of the C++
/// `set_log_sink(nullptr)` path.
/// The installed sink, or `None` when the built-in stdio sink is active.
///
/// The C++ `get_log_sink()` always returns a callable because its default is
/// itself a `std::function`. Here `None` distinguishes "default" from
/// "consumer-installed", which the C++ side cannot express.
/// The built-in sink: errors and warnings to stderr, info and debug to stdout,
/// each line prefixed `[drm:LEVEL] `.
///
/// Write failures are swallowed. A logger that panics or aborts because stderr
/// is a closed pipe would turn a diagnostic into an outage — the C++ side has
/// the same behavior by way of ignoring `fprintf`'s return.
/// Format and deliver a record to the active sink, bypassing the level gate.
///
/// Not part of the stable surface — the `log_*!` macros call it after they
/// have checked the level. Visible because macros expand in the caller's
/// crate.