minimal_logger 0.7.0

A minimal-resource, platform-native logger for Rust applications.
Documentation
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
use std::fmt::Write;
use std::path::{PathBuf, absolute};
use std::sync::OnceLock;

use log::{LevelFilter, Record};
use time::OffsetDateTime;

use crate::logger::FileTarget;

/// Default capacity of each thread-local [`BufWriter`], in bytes.
pub(crate) const DEFAULT_BUF_CAPACITY: usize = 4 * 1024;
/// Maximum accepted capacity of each thread-local [`BufWriter`], in bytes.
pub(crate) const MAX_BUF_CAPACITY: usize = 1024 * 1024;
/// Default interval at which the flush worker wakes and sets `FLUSH_FLAG`, in milliseconds.
pub(crate) const DEFAULT_FLUSH_MS: u64 = 1_000;
/// Maximum periodic flush interval accepted from builder/env configuration.
pub(crate) const MAX_FLUSH_MS: u64 = 60 * 60 * 1_000;
/// Default log-line template used when `RUST_LOG_FORMAT` is not set.
pub(crate) const DEFAULT_LOG_FORMAT: &str =
    "{timestamp} [{level:<5}] T[{thread_name}] [{target}] {args}";
/// Maximum accepted log-line format template length, in bytes.
pub(crate) const MAX_FORMAT_TEMPLATE_LEN: usize = 8 * 1024;
/// Maximum accepted width for a single formatted field.
pub(crate) const MAX_FORMAT_FIELD_WIDTH: usize = 4 * 1024;
/// Maximum number of accepted `target=level` filters.
pub(crate) const MAX_FILTERS: usize = 128;
/// Maximum accepted length of a filter target, in bytes.
pub(crate) const MAX_FILTER_TARGET_LEN: usize = 256;

/// A snapshot of resolved logger configuration.
///
/// Produced by [`MinimalLoggerConfig::into_reload`] and compared against the currently
/// active configuration by [`MinimalLogger::apply_reload`]. Equal snapshots
/// mean no reconfiguration is required.
#[derive(Clone, PartialEq, Eq)]
pub(crate) struct ReloadConfig {
    /// Fallback level used when no per-target filter matches.
    pub(crate) default_level: LevelFilter,
    /// Per-target overrides, sorted by decreasing `target` length for prefix matching.
    pub(crate) filters: Vec<TargetFilter>,
    /// Absolute path to the log file, or `None` for stderr mode.
    pub(crate) file_path: Option<String>,
    /// Desired capacity of each new thread-local `BufWriter`, in bytes.
    pub(crate) buf_capacity: usize,
    /// Flush worker sleep interval, in milliseconds.
    pub(crate) flush_ms: u64,
    /// Raw `RUST_LOG_FORMAT` string kept for equality comparison and re-parsing.
    pub(crate) format_template: String,
}

/// Live runtime configuration derived from a [`ReloadConfig`] snapshot.
///
/// Stored behind an `Arc` inside an [`ArcSwap`] so that [`reinit()`] can swap
/// it atomically while concurrent log calls read it without any locking.
#[derive(Clone)]
pub(crate) struct ActiveConfig {
    /// The environment snapshot this config was compiled from.
    pub(crate) reload: ReloadConfig,
    /// Compiled format template used to render each log record.
    pub(crate) format: LogFormat,
    /// Pre-computed maximum level across all filters; passed to `log::set_max_level`.
    pub(crate) max_level: LevelFilter,
}

impl ActiveConfig {
    /// Build an `ActiveConfig` from a freshly parsed [`ReloadConfig`].
    ///
    /// Compiles the format template and computes the global maximum level.
    pub(crate) fn from_reload(reload: ReloadConfig) -> Self {
        let max_level = reload
            .filters
            .iter()
            .map(|f| f.level)
            .fold(reload.default_level, |acc, level| acc.max(level));

        ActiveConfig {
            format: LogFormat::parse(&reload.format_template),
            reload,
            max_level,
        }
    }

    /// Return the effective [`LevelFilter`] for the given log target.
    ///
    /// Finds the most-specific matching filter (longest target prefix) or falls
    /// back to `default_level` when no filter matches.
    #[inline]
    pub(crate) fn level_for(&self, target: &str) -> LevelFilter {
        self.reload
            .filters
            .iter()
            .find(|f| target.starts_with(f.target.as_str()))
            .map(|f| f.level)
            .unwrap_or(self.reload.default_level)
    }
}

/// Builder for logger configuration.
///
/// Construct with [`MinimalLoggerConfig::new()`] (or [`Default::default()`]) for fully
/// programmatic configuration, or with [`MinimalLoggerConfig::from_env()`] to seed the config from
/// the standard `RUST_LOG*` environment variables. Chain builder methods to set or
/// override individual settings, then pass the result to [`init()`] or [`reinit()`].
///
/// # Unset fields
///
/// On [`init()`], any unset field falls back to its compile-time default:
/// `Info` level, stderr output, 4 KiB buffer, 1 s flush interval, and the
/// built-in timestamp/level/thread/file/line format.
/// Oversized buffer sizes, flush intervals, format templates, format widths,
/// and filter lists are bounded to avoid accidental memory or latency spikes
/// from environment-derived configuration.
///
/// On [`reinit()`], any unset field **keeps its current value** — so you can
/// update a single subsystem without touching the others:
///
/// ```rust,no_run
/// minimal_logger::reinit(
///     minimal_logger::MinimalLoggerConfig::new().level(log::LevelFilter::Debug)
/// );
/// ```
///
/// # Example
///
/// ```rust,no_run
/// let _guard = minimal_logger::init(
///     minimal_logger::MinimalLoggerConfig::new()
///         .level(log::LevelFilter::Info)
///         .filter("myapp::db", log::LevelFilter::Debug)
///         .format("{timestamp} [{level}] {args}")
/// ).expect("logger init failed");
/// ```
pub struct MinimalLoggerConfig {
    pub(crate) level: Option<LevelFilter>,
    pub(crate) filters: Option<Vec<(String, LevelFilter)>>,
    pub(crate) file: Option<FileTarget>,
    pub(crate) buf_capacity: Option<usize>,
    pub(crate) flush_ms: Option<u64>,
    pub(crate) format: Option<String>,
}

impl Default for MinimalLoggerConfig {
    fn default() -> Self {
        Self::new()
    }
}

fn bounded_buf_capacity(bytes: usize) -> usize {
    if bytes > MAX_BUF_CAPACITY {
        eprintln!("[minimal_logger] Buffer size {bytes} exceeds max {MAX_BUF_CAPACITY} — clamping");
        MAX_BUF_CAPACITY
    } else {
        bytes
    }
}

fn bounded_flush_ms(ms: u64) -> u64 {
    if ms > MAX_FLUSH_MS {
        eprintln!("[minimal_logger] Flush interval {ms}ms exceeds max {MAX_FLUSH_MS}ms — clamping");
        MAX_FLUSH_MS
    } else {
        ms
    }
}

fn bounded_format_template(template: String) -> String {
    if template.len() > MAX_FORMAT_TEMPLATE_LEN {
        eprintln!(
            "[minimal_logger] Format template is {} bytes; max is {MAX_FORMAT_TEMPLATE_LEN} — using default",
            template.len()
        );
        DEFAULT_LOG_FORMAT.to_string()
    } else {
        template
    }
}

fn bounded_format_width(width: usize) -> usize {
    if width > MAX_FORMAT_FIELD_WIDTH {
        eprintln!(
            "[minimal_logger] Format field width {width} exceeds max {MAX_FORMAT_FIELD_WIDTH} — clamping"
        );
        MAX_FORMAT_FIELD_WIDTH
    } else {
        width
    }
}

impl MinimalLoggerConfig {
    /// Create a new `MinimalLoggerConfig` with all fields unset.
    ///
    /// See the struct documentation for how unset fields are resolved inside
    /// [`init()`] and [`reinit()`].
    pub fn new() -> Self {
        MinimalLoggerConfig {
            level: None,
            filters: None,
            file: None,
            buf_capacity: None,
            flush_ms: None,
            format: None,
        }
    }

    /// Set the global default log level.
    ///
    /// Records whose target does not match any per-target filter (added via
    /// [`filter`](Self::filter)) are emitted at this level or above.
    pub fn level(mut self, level: LevelFilter) -> Self {
        self.level = Some(level);
        self
    }

    /// Add a per-target level override.
    ///
    /// `target` is matched as a prefix of the log record's target string
    /// (typically the module path). The most specific (longest) matching
    /// prefix wins. May be called multiple times, up to an internal safety cap.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// let _guard = minimal_logger::init(
    ///     minimal_logger::MinimalLoggerConfig::new()
    ///         .level(log::LevelFilter::Warn)                 // global default
    ///         .filter("myapp", log::LevelFilter::Info)       // myapp and submodules
    ///         .filter("myapp::db", log::LevelFilter::Trace)  // db at trace
    /// ).expect("logger init failed");
    /// ```
    pub fn filter(mut self, target: impl Into<String>, level: LevelFilter) -> Self {
        let target = target.into();
        if target.len() > MAX_FILTER_TARGET_LEN {
            eprintln!(
                "[minimal_logger] Filter target {:?} exceeds max {MAX_FILTER_TARGET_LEN} bytes — skipping",
                target
            );
            return self;
        }

        let filters = self.filters.get_or_insert_with(Vec::new);
        if filters.len() >= MAX_FILTERS {
            eprintln!("[minimal_logger] Filter count exceeds max {MAX_FILTERS} — skipping");
            return self;
        }
        filters.push((target, level));
        self
    }

    /// Write log output to a file at `path` (created with `O_APPEND` if absent).
    ///
    /// The path is resolved to an absolute path when the configuration is applied
    /// (inside [`init()`] or [`reinit()`]). On Unix, newly created files use
    /// owner-only permissions subject to the process umask. If the file cannot
    /// be opened, a diagnostic is printed to stderr and output falls back to stderr.
    pub fn file(mut self, path: impl Into<PathBuf>) -> Self {
        self.file = Some(FileTarget::Path(path.into()));
        self
    }

    /// Write log output to standard error (the default).
    ///
    /// Use this on [`reinit()`] to switch back from a log file to stderr.
    pub fn stderr(mut self) -> Self {
        self.file = Some(FileTarget::Stderr);
        self
    }

    /// Set the per-thread [`BufWriter`] capacity in bytes (default: 4096).
    ///
    /// The new capacity takes effect the next time a thread's writer is
    /// recreated (on first use or after a log-file rotation). Values above the
    /// internal safety cap are clamped.
    pub fn buf_capacity(mut self, bytes: usize) -> Self {
        self.buf_capacity = Some(bounded_buf_capacity(bytes));
        self
    }

    /// Set the periodic flush interval in milliseconds (default: 1000).
    ///
    /// A background thread wakes every `ms` milliseconds and sets a flag that
    /// causes the next log call on any thread to flush its buffer. Set to `0`
    /// to flush on every log record without spawning a background thread. Values
    /// above the internal safety cap are clamped.
    pub fn flush_ms(mut self, ms: u64) -> Self {
        self.flush_ms = Some(bounded_flush_ms(ms));
        self
    }

    /// Set the log-line format template.
    ///
    /// The template is a string with `{field}` placeholders. Supported fields:
    /// `timestamp`, `level`, `thread_name`, `target`, `module_path`, `file`,
    /// `line`, `args`. Width/alignment follows `{level:<5}` syntax. Use `{{`
    /// and `}}` for literal brace characters.
    ///
    /// Default: `{timestamp} [{level:<5}] T[{thread_name}] [{target}] {args}`
    ///
    /// Very large templates and field widths are bounded to avoid unexpectedly
    /// large per-record allocations.
    pub fn format(mut self, template: impl Into<String>) -> Self {
        self.format = Some(bounded_format_template(template.into()));
        self
    }

    /// Return the configured global log level, if set.
    pub fn get_level(&self) -> Option<LevelFilter> {
        self.level
    }

    /// Return the configured per-target filters as a slice of `(target, level)` pairs.
    pub fn get_filters(&self) -> &[(String, LevelFilter)] {
        self.filters.as_deref().unwrap_or(&[])
    }

    /// Return the configured log file path, if set.
    pub fn get_file_path(&self) -> Option<&std::path::Path> {
        match &self.file {
            Some(FileTarget::Path(p)) => Some(p.as_path()),
            _ => None,
        }
    }

    /// Return the configured per-thread buffer capacity in bytes, if set.
    pub fn get_buf_capacity(&self) -> Option<usize> {
        self.buf_capacity
    }

    /// Return the configured flush interval in milliseconds, if set.
    pub fn get_flush_ms(&self) -> Option<u64> {
        self.flush_ms
    }

    /// Return the configured log-line format template string, if set.
    pub fn get_format(&self) -> Option<&str> {
        self.format.as_deref()
    }

    /// Build a [`MinimalLoggerConfig`] from the standard `RUST_LOG*` environment variables.
    ///
    /// This is the only public API surface that reads environment variables. The
    /// returned config can be inspected or further modified with builder methods before
    /// being passed to [`init()`] or [`reinit()`].
    ///
    /// | Variable               | Description                                          |
    /// |------------------------|------------------------------------------------------|
    /// | `RUST_LOG`             | Global level and optional `target=level` overrides   |
    /// | `RUST_LOG_FILE`        | Path to the log file (omit for stderr output)        |
    /// | `RUST_LOG_BUFFER_SIZE` | Per-thread `BufWriter` capacity in bytes             |
    /// | `RUST_LOG_FLUSH_MS`    | Periodic flush interval in milliseconds              |
    /// | `RUST_LOG_FORMAT`      | Log-line template with `{field}` placeholders        |
    ///
    /// When `RUST_LOG` is unset it defaults to `info`. All other variables, when absent
    /// or unparseable, leave the corresponding builder field as `None`: on [`init()`]
    /// that resolves to the compile-time default (4096 B buffer, 1 s flush, built-in
    /// format, stderr output); on [`reinit()`] it preserves the currently active value.
    /// Invalid `RUST_LOG` directives are skipped with a warning on stderr.
    /// Oversized values are clamped or replaced with safe defaults.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// // Read env vars, then override the level programmatically before init.
    /// let config = minimal_logger::MinimalLoggerConfig::from_env()
    ///     .level(log::LevelFilter::Debug);
    /// let _guard = minimal_logger::init(config).expect("logger init failed");
    /// ```
    pub fn from_env() -> MinimalLoggerConfig {
        let rust_log = std::env::var("RUST_LOG").unwrap_or_else(|_| "info".to_string());

        let file = std::env::var("RUST_LOG_FILE")
            .ok()
            .map(|path| FileTarget::Path(PathBuf::from(path)));

        let buf_capacity = std::env::var("RUST_LOG_BUFFER_SIZE")
            .ok()
            .and_then(|s| s.parse().ok())
            .map(bounded_buf_capacity);

        let flush_ms = std::env::var("RUST_LOG_FLUSH_MS")
            .ok()
            .and_then(|s| s.parse().ok())
            .map(bounded_flush_ms);

        let format = std::env::var("RUST_LOG_FORMAT")
            .ok()
            .map(bounded_format_template);

        let mut level: Option<LevelFilter> = None;
        let mut filters: Vec<(String, LevelFilter)> = Vec::new();

        for directive in rust_log.split(',').map(str::trim).filter(|s| !s.is_empty()) {
            match directive.split_once('=') {
                Some((target, level_str)) => {
                    let target = target.trim();
                    if filters.len() >= MAX_FILTERS {
                        eprintln!(
                            "[minimal_logger] RUST_LOG: too many filters — ignoring remaining"
                        );
                        break;
                    }
                    if target.len() > MAX_FILTER_TARGET_LEN {
                        eprintln!(
                            "[minimal_logger] RUST_LOG: filter target {:?} exceeds max {MAX_FILTER_TARGET_LEN} bytes — skipping",
                            target
                        );
                        continue;
                    }
                    match level_str.trim().parse::<LevelFilter>() {
                        Ok(l) => filters.push((target.to_string(), l)),
                        Err(_) => eprintln!(
                            "[minimal_logger] RUST_LOG: unknown level {:?} — skipping",
                            level_str
                        ),
                    }
                }
                None => match directive.parse::<LevelFilter>() {
                    Ok(l) => level = Some(l),
                    Err(_) => eprintln!(
                        "[minimal_logger] RUST_LOG: unknown directive {:?} — skipping",
                        directive
                    ),
                },
            }
        }

        MinimalLoggerConfig {
            level,
            filters: if filters.is_empty() {
                None
            } else {
                Some(filters)
            },
            file,
            buf_capacity,
            flush_ms,
            format,
        }
    }

    /// Convert this builder into a [`ReloadConfig`], merging with `current`.
    ///
    /// Each unset field inherits from `current` when `Some`, or falls back to
    /// the compile-time default when `None` (the case during [`init()`]).
    pub(crate) fn into_reload(self, current: Option<&ReloadConfig>) -> ReloadConfig {
        let default_level = self
            .level
            .unwrap_or_else(|| current.map_or(LevelFilter::Info, |c| c.default_level));

        let filters = match self.filters {
            Some(vec) => {
                let mut tf: Vec<TargetFilter> = vec
                    .into_iter()
                    .map(|(target, level)| TargetFilter { target, level })
                    .collect();
                tf.sort_unstable_by(|a, b| b.target.len().cmp(&a.target.len()));
                tf
            }
            None => current.map_or_else(Vec::new, |c| c.filters.clone()),
        };

        let file_path = match self.file {
            Some(FileTarget::Path(p)) => {
                let abs = match absolute(&p) {
                    Ok(a) => a,
                    Err(e) => {
                        eprintln!(
                            "[minimal_logger] Could not resolve absolute path for {:?}: {e} — using path as-is",
                            p
                        );
                        p
                    }
                };
                Some(abs.display().to_string())
            }
            Some(FileTarget::Stderr) => None,
            None => current.and_then(|c| c.file_path.clone()),
        };

        let buf_capacity = bounded_buf_capacity(
            self.buf_capacity
                .unwrap_or_else(|| current.map_or(DEFAULT_BUF_CAPACITY, |c| c.buf_capacity)),
        );

        let flush_ms = bounded_flush_ms(
            self.flush_ms
                .unwrap_or_else(|| current.map_or(DEFAULT_FLUSH_MS, |c| c.flush_ms)),
        );

        let format_template = bounded_format_template(self.format.unwrap_or_else(|| {
            current.map_or_else(
                || DEFAULT_LOG_FORMAT.to_string(),
                |c| c.format_template.clone(),
            )
        }));

        ReloadConfig {
            default_level,
            filters,
            file_path,
            buf_capacity,
            flush_ms,
            format_template,
        }
    }
}

/// Build a [`MinimalLoggerConfig`] from the standard `RUST_LOG*` environment variables.
///
/// This is a convenience free function that delegates to
/// [`MinimalLoggerConfig::from_env()`].
///
/// # Deprecation
///
/// Prefer calling [`MinimalLoggerConfig::from_env()`] directly. This free
/// function is retained for backward compatibility and will be removed in a
/// future major version.
///
/// # Example
///
/// ```rust,no_run
/// let _guard = minimal_logger::init(minimal_logger::config_from_env()).expect("logger init failed");
/// ```
#[deprecated(
    since = "0.3.0",
    note = "Use `MinimalLoggerConfig::from_env()` instead"
)]
pub fn config_from_env() -> MinimalLoggerConfig {
    MinimalLoggerConfig::from_env()
}

/// A single `target=level` directive parsed from the `RUST_LOG` environment variable.
///
/// Directives are sorted by decreasing `target` length before matching so that
/// the most specific prefix always wins.
#[derive(Clone, PartialEq, Eq, Debug)]
pub(crate) struct TargetFilter {
    /// Module or crate path prefix matched against `record.target()`.
    pub(crate) target: String,
    /// Maximum level to emit for records whose target starts with `self.target`.
    pub(crate) level: LevelFilter,
}

/// Horizontal alignment direction for a fixed-width format field.
#[derive(Clone, Copy)]
enum Align {
    /// Pad on the right; the value appears at the left edge of the field.
    Left,
    /// Pad on the left; the value appears at the right edge of the field.
    Right,
}

/// Width and alignment parsed from the `:spec` portion of a `{field:spec}` placeholder.
#[derive(Clone, Copy)]
struct FormatSpec {
    /// Direction of space padding.
    align: Align,
    /// Minimum rendered width in characters; `None` means no padding.
    width: Option<usize>,
}

/// A named field that can appear as a `{field}` placeholder in `RUST_LOG_FORMAT`.
#[derive(Clone, Copy)]
enum LogField {
    /// UTC timestamp with microsecond precision (`2026-04-18T12:34:56.789012Z`).
    Timestamp,
    /// Name of the current thread, or `"unnamed"` if none was set.
    ThreadName,
    /// Log level string (`ERROR`, `WARN`, `INFO`, `DEBUG`, `TRACE`).
    Level,
    /// The `log::Record` target, typically the module path of the call site.
    Target,
    /// The formatted log message; `{message}` is an accepted synonym.
    Args,
    /// Rust module path of the call site.
    ModulePath,
    /// Source file name of the call site.
    File,
    /// Source line number of the call site.
    Line,
}

/// One element of a compiled `RUST_LOG_FORMAT` template.
#[derive(Clone)]
enum FormatPiece {
    /// Verbatim text copied directly to the output without substitution.
    Literal(String),
    /// A `{field}` or `{field:spec}` placeholder rendered at log call time.
    Placeholder { field: LogField, spec: FormatSpec },
}

/// A compiled log-line format template.
///
/// Built once from a `RUST_LOG_FORMAT` string via [`LogFormat::parse`] and
/// cloned into each new [`ActiveConfig`]. Rendering on the hot path allocates
/// only the final output `String`.
#[derive(Clone)]
pub(crate) struct LogFormat {
    /// Ordered sequence of literal segments and field placeholders.
    pieces: Vec<FormatPiece>,
}

impl LogFormat {
    /// Compile a `RUST_LOG_FORMAT` template string into a [`LogFormat`].
    ///
    /// `{field}` and `{field:spec}` sequences become [`FormatPiece::Placeholder`]
    /// entries; `{{` and `}}` are unescaped to literal brace characters.
    /// Unrecognised field names are kept as literal `{name}` text.
    pub(crate) fn parse(format: &str) -> Self {
        let mut pieces = Vec::new();
        let mut literal = String::new();
        let mut chars = format.chars().peekable();

        while let Some(ch) = chars.next() {
            match ch {
                '{' => {
                    if chars.peek() == Some(&'{') {
                        chars.next();
                        literal.push('{');
                        continue;
                    }

                    if !literal.is_empty() {
                        pieces.push(FormatPiece::Literal(std::mem::take(&mut literal)));
                    }

                    let mut token = String::new();
                    for next in chars.by_ref() {
                        if next == '}' {
                            break;
                        }
                        token.push(next);
                    }

                    let piece = if token.is_empty() {
                        FormatPiece::Literal("{}".to_string())
                    } else {
                        parse_placeholder(&token)
                    };
                    pieces.push(piece);
                }
                '}' => {
                    if chars.peek() == Some(&'}') {
                        chars.next();
                        literal.push('}');
                    } else {
                        literal.push('}');
                    }
                }
                other => literal.push(other),
            }
        }

        if !literal.is_empty() {
            pieces.push(FormatPiece::Literal(literal));
        }

        LogFormat { pieces }
    }

    /// Render a log [`Record`] against this template into a complete log line.
    ///
    /// All field values are written directly into `output` without intermediate
    /// `String` heap allocations — only the final output buffer is allocated.
    /// Appends a trailing `'\n'` if the rendered string does not already end
    /// with one.
    pub(crate) fn render(&self, record: &Record) -> String {
        let mut output = String::new();

        for piece in &self.pieces {
            match piece {
                FormatPiece::Literal(text) => output.push_str(text),
                FormatPiece::Placeholder { field, spec } => {
                    write_field(&mut output, *field, *spec, record);
                }
            }
        }

        if !output.ends_with('\n') {
            output.push('\n');
        }

        output
    }
}

/// Parse the text between `{` and `}` into a [`FormatPiece`].
///
/// Splits on `:` to separate the field name from an optional format spec.
/// Returns a [`FormatPiece::Literal`] if the field name is not recognised.
fn parse_placeholder(token: &str) -> FormatPiece {
    let (name, spec_text) = token.split_once(':').unwrap_or((token, ""));
    let spec = parse_format_spec(spec_text);

    let field = match name {
        "timestamp" => LogField::Timestamp,
        "thread_name" => LogField::ThreadName,
        "level" => LogField::Level,
        "target" => LogField::Target,
        "args" | "message" => LogField::Args,
        "module_path" => LogField::ModulePath,
        "file" => LogField::File,
        "line" => LogField::Line,
        _ => {
            return FormatPiece::Literal(format!("{{{}}}", token));
        }
    };

    FormatPiece::Placeholder { field, spec }
}

/// Parse the spec portion of a `{field:spec}` placeholder into a [`FormatSpec`].
///
/// Accepts `<N` (left-align, width N) and `>N` (right-align, width N).
/// Returns a zero-width, left-aligned spec for unrecognised or empty input.
fn parse_format_spec(spec: &str) -> FormatSpec {
    if let Some(width_text) = spec.strip_prefix('<')
        && let Ok(width) = width_text.parse::<usize>()
    {
        return FormatSpec {
            align: Align::Left,
            width: Some(bounded_format_width(width)),
        };
    }

    if let Some(width_text) = spec.strip_prefix('>')
        && let Ok(width) = width_text.parse::<usize>()
    {
        return FormatSpec {
            align: Align::Right,
            width: Some(bounded_format_width(width)),
        };
    }

    FormatSpec {
        align: Align::Left,
        width: None,
    }
}

/// Cached timestamp `FormatDescription` — parsed once, reused on every log call.
static TIMESTAMP_FMT: OnceLock<time::format_description::OwnedFormatItem> = OnceLock::new();

/// Write a single [`LogField`] into `out`, applying `spec` padding inline.
///
/// Writing directly into `out` avoids the intermediate `String` that the old
/// `render_field` + `apply_format_spec` pair produced per placeholder.
fn write_field(out: &mut String, field: LogField, spec: FormatSpec, record: &Record) {
    // Helper: write `value` str with padding applied.
    fn write_padded(out: &mut String, value: &str, spec: FormatSpec) {
        match spec.width {
            Some(w) if value.len() < w => {
                let pad = w - value.len();
                match spec.align {
                    Align::Left => {
                        out.push_str(value);
                        for _ in 0..pad {
                            out.push(' ');
                        }
                    }
                    Align::Right => {
                        for _ in 0..pad {
                            out.push(' ');
                        }
                        out.push_str(value);
                    }
                }
            }
            _ => out.push_str(value),
        }
    }

    match field {
        LogField::Timestamp => {
            let fmt = TIMESTAMP_FMT.get_or_init(|| {
                time::format_description::parse_owned::<1>(
                    "[year]-[month]-[day]T[hour]:[minute]:[second].[subsecond digits:6]Z",
                )
                .expect("timestamp format string is valid")
            });
            let now = OffsetDateTime::now_utc();
            match now.format(fmt) {
                Ok(ts) => write_padded(out, &ts, spec),
                Err(_) => write_padded(out, "unknown-time", spec),
            }
        }
        LogField::ThreadName => {
            let t = std::thread::current();
            write_padded(out, t.name().unwrap_or("unnamed"), spec);
        }
        LogField::Level => {
            write_padded(out, record.level().as_str(), spec);
        }
        LogField::Target => {
            write_padded(out, record.target(), spec);
        }
        LogField::Args => {
            // `record.args()` is a `fmt::Arguments` — write it directly to
            // avoid a temporary String when no padding is required.
            match spec.width {
                None => {
                    let _ = write!(out, "{}", record.args());
                }
                Some(_) => {
                    let s = record.args().to_string();
                    write_padded(out, &s, spec);
                }
            }
        }
        LogField::ModulePath => {
            write_padded(out, record.module_path().unwrap_or_default(), spec);
        }
        LogField::File => {
            write_padded(out, record.file().unwrap_or_default(), spec);
        }
        LogField::Line => {
            if let Some(n) = record.line() {
                if spec.width.is_none() {
                    let _ = write!(out, "{n}");
                } else {
                    let s = n.to_string();
                    write_padded(out, &s, spec);
                }
            }
        }
    }
}