Skip to main content

cortexkit_log/
lib.rs

1//! A synchronous `tracing` layer for CortexKit's module-owned fleet logs.
2//!
3//! One crate, one format, one file per module per day. Every line follows the
4//! stable fleet logging format pinned by the crate's golden fixtures.
5//!
6//! A [`Crates`] policy labels dependency events `<module_id>.dep.<crate>`, with
7//! underscores in Rust crate names written as hyphens. Dependencies default to
8//! WARN or the module's own level, whichever is lower; a matching `CK_LOG`
9//! directive can raise that level. Per-crate ceilings always win, including an
10//! OFF ceiling for dependencies whose verbose output may expose credentials or
11//! connection details. An outer `filter_fn` cannot bypass the layer's
12//! per-event level and ceiling checks, although its own predicate can suppress
13//! events; it is unnecessary for enforcing `CK_LOG`.
14
15mod filter;
16mod format;
17mod redaction;
18mod segment;
19mod sink;
20
21pub use segment::{prune_candidates, segment_day, segment_name, SegmentRetention};
22pub use sink::LineSink;
23
24use std::backtrace::Backtrace;
25use std::borrow::Cow;
26use std::collections::{HashMap, HashSet};
27use std::env;
28use std::fmt;
29use std::io::{self, Write};
30use std::panic;
31use std::path::{Path, PathBuf};
32use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
33use std::sync::{Arc, Mutex, OnceLock};
34use std::time::SystemTime;
35
36use filter::LevelFilter as CkLogFilter;
37pub use format::{ParseError, ParsedLevel, ParsedLine};
38use redaction::fleet_redact;
39use segment::{SegmentDestination, SegmentNotice};
40use tracing::field::{Field, Visit};
41use tracing::span::{Attributes, Id, Record};
42use tracing::{Event, Metadata, Subscriber};
43pub use tracing_subscriber::filter::LevelFilter;
44use tracing_subscriber::layer::{Context, SubscriberExt};
45use tracing_subscriber::registry::LookupSpan;
46use tracing_subscriber::{Layer, Registry};
47
48static WRITE_FAILURE_REPORTED: AtomicBool = AtomicBool::new(false);
49static FILTER_FAILURE_REPORTED: AtomicBool = AtomicBool::new(false);
50
51/// Size and age bounds for the rename-rotated [`LineSink`], which has exactly
52/// one writer (the daemon's per-child stderr capture). The logger's own
53/// segments use [`SegmentRetention`]; the two are different files with
54/// different writer counts, and only the single-writer one may rename.
55#[derive(Clone, Copy, Debug, Eq, PartialEq)]
56pub struct Retention {
57    /// Maximum active-file size in mebibytes.
58    pub max_file_mb: u32,
59    /// Number of rotated generations to retain.
60    pub keep: u8,
61    /// Maximum age of rotated generations in days.
62    pub max_age_days: u32,
63}
64
65impl Default for Retention {
66    fn default() -> Self {
67        Self {
68            max_file_mb: 32,
69            keep: 2,
70            max_age_days: 14,
71        }
72    }
73}
74
75impl Retention {
76    const TEST_BYTES_MARKER: u32 = 1 << 31;
77
78    /// Constructs a byte-sized cap so retention tests do not write whole MiB files.
79    #[doc(hidden)]
80    pub fn from_bytes_for_testing(max_file_bytes: u32, keep: u8, max_age_days: u32) -> Self {
81        assert!(max_file_bytes < Self::TEST_BYTES_MARKER);
82        Self {
83            max_file_mb: Self::TEST_BYTES_MARKER | max_file_bytes,
84            keep,
85            max_age_days,
86        }
87    }
88
89    pub(crate) fn max_bytes(self) -> u64 {
90        if self.max_file_mb & Self::TEST_BYTES_MARKER != 0 {
91            return u64::from(self.max_file_mb & !Self::TEST_BYTES_MARKER);
92        }
93
94        u64::from(self.max_file_mb) * 1024 * 1024
95    }
96}
97
98/// A complete-line redactor composed after the fleet credential redactor.
99pub type Redactor = dyn for<'line> Fn(&'line str) -> Cow<'line, str> + Send + Sync;
100
101/// Logger names for dependency crates and maximum levels for crates and modules.
102///
103/// `Crates::own` takes crate names in Rust spelling, for example
104/// `my_module_core`; events from those crates retain the logger-name behavior used
105/// without a crate policy. Other crates are labelled `<module_id>.dep.<crate>`, with
106/// underscores changed to hyphens. Unless a `CK_LOG` directive names a
107/// dependency, its level is capped at WARN or the module's own resolved level,
108/// whichever is lower. Ceilings are enforced after all `CK_LOG` directives and
109/// rechecked while writing, so an outer `filter_fn` cannot bypass them, although
110/// its own predicate can still suppress events.
111///
112/// Pair this with `cortexkit-bus-client` 0.1.17's outage logs to drop redundant
113/// reconnect and handshake logs while keeping async-nats's other warnings and
114/// errors:
115///
116/// ```
117/// use cortexkit_log::{Crates, LevelFilter};
118///
119/// let crates = Crates::new()
120///     .ceiling("async_nats", LevelFilter::WARN)
121///     .ceiling("async_nats::connector", LevelFilter::OFF);
122/// ```
123#[non_exhaustive]
124#[derive(Clone, Debug, Default)]
125pub struct Crates {
126    own: HashSet<String>,
127    ceilings: HashMap<String, Option<tracing::Level>>,
128}
129
130impl Crates {
131    /// Creates an empty crate policy.
132    pub fn new() -> Self {
133        Self::default()
134    }
135
136    /// Adds crate names that belong to this module rather than its dependencies.
137    ///
138    /// Events from these crates keep the logger-name behavior used without a
139    /// crate policy.
140    pub fn own<I, S>(mut self, crate_names: I) -> Self
141    where
142        I: IntoIterator<Item = S>,
143        S: Into<String>,
144    {
145        self.own.extend(crate_names.into_iter().map(Into::into));
146        self
147    }
148
149    /// Sets the maximum level for a dependency crate or a Rust module path.
150    ///
151    /// Use Rust spelling, such as `transport_layer` or `transport_layer::retry`.
152    /// The event's module path (or target if absent) matches on `::` boundaries.
153    /// The most specific ceiling wins, regardless of insertion order. Module
154    /// path ceilings also apply to [`Self::own`] crates, which ignore bare crate
155    /// ceilings. Neither type of ceiling changes the logger name.
156    ///
157    /// The ceiling applies after `CK_LOG`; no directive can raise the event's
158    /// level above it. An OFF ceiling drops matching events. Ceilings can keep
159    /// verbose transport output containing credentials out of the logs.
160    pub fn ceiling(mut self, crate_or_module: impl Into<String>, level: LevelFilter) -> Self {
161        let level = match level.to_string().to_ascii_lowercase().as_str() {
162            "off" => None,
163            "error" => Some(tracing::Level::ERROR),
164            "warn" => Some(tracing::Level::WARN),
165            "info" => Some(tracing::Level::INFO),
166            "debug" => Some(tracing::Level::DEBUG),
167            "trace" => Some(tracing::Level::TRACE),
168            _ => unreachable!("tracing level filters have a fixed set of levels"),
169        };
170        self.ceilings.insert(crate_or_module.into(), level);
171        self
172    }
173
174    fn ceiling_for(
175        &self,
176        mut module_path: &str,
177        dependency: bool,
178    ) -> Option<Option<tracing::Level>> {
179        if self.ceilings.is_empty() {
180            return None;
181        }
182        while let Some((parent, _)) = module_path.rsplit_once("::") {
183            if let Some(level) = self.ceilings.get(module_path) {
184                return Some(*level);
185            }
186            module_path = parent;
187        }
188        if dependency {
189            self.ceilings.get(module_path).copied()
190        } else {
191            None
192        }
193    }
194}
195
196/// Logger configuration for one process.
197pub struct Config {
198    /// Stable fleet module identifier: the root of every logger name and the
199    /// first part of every segment's file name.
200    pub module_id: String,
201    /// The directory the segments live in. Fleet callers never assemble this:
202    /// [`Config::for_module`] derives it from the module id through the same
203    /// resolver every store uses, so a log cannot land beside the wrong data.
204    /// Public for tests and for the daemon's own `run/logs/` lane, which is not
205    /// a module data directory.
206    pub logs_dir: PathBuf,
207    /// Fields bound for the whole process and rendered in the bracket on every
208    /// line, in this order. A harness-hosted plugin binds `harness=<name>`
209    /// here: after r2 every lane shares one segment and this is what tells
210    /// them apart.
211    pub bound: Vec<(String, String)>,
212    /// `CK_LOG` override; `None` reads the process environment.
213    pub spec: Option<String>,
214    /// Age window and oversize alarm for the segments.
215    pub retention: SegmentRetention,
216    /// Optional module redactor, applied after fleet credential redaction.
217    pub redactor: Option<Arc<Redactor>>,
218    /// Optional clock override for deterministic callers and tests.
219    pub clock: Option<Arc<dyn Fn() -> SystemTime + Send + Sync>>,
220}
221
222impl Config {
223    /// A configuration whose segment directory the caller already resolved:
224    /// `CK_LOG` from the environment, fleet default retention, nothing bound.
225    /// This is the path for a consumer that owns its module data directory
226    /// through its own pinned store crate and must not pull a second copy of
227    /// it through this one (see the `store-paths` feature).
228    pub fn in_dir(module_id: &str, logs_dir: impl Into<PathBuf>) -> Self {
229        Self {
230            module_id: module_id.to_owned(),
231            logs_dir: logs_dir.into(),
232            bound: Vec::new(),
233            spec: None,
234            retention: SegmentRetention::default(),
235            redactor: None,
236            clock: None,
237        }
238    }
239
240    /// The fleet configuration for a supervised module's own process: segments
241    /// under `<module data dir>/logs/`, `CK_LOG` from the environment (the
242    /// daemon injects it at spawn), fleet default retention, nothing bound.
243    #[cfg(feature = "store-paths")]
244    pub fn for_module(module_id: &str) -> Self {
245        let data_dir = PathBuf::from(cortexkit_store_types::module_data_dir(module_id));
246        Self::in_dir(module_id, data_dir.join("logs"))
247    }
248
249    /// [`Config::for_module`] with `harness=<harness>` bound on every line, for
250    /// a plugin running inside a harness process.
251    #[cfg(feature = "store-paths")]
252    pub fn for_plugin(module_id: &str, harness: &str) -> Self {
253        let mut config = Self::for_module(module_id);
254        config
255            .bound
256            .push(("harness".to_owned(), harness.to_owned()));
257        config
258    }
259
260    /// The configuration a supervised module can build with no arguments,
261    /// because the daemon already injects everything it needs at spawn:
262    /// `SUBC_MODULE_ID` (for launch attestation), `CK_LOG`, and the retention
263    /// knobs as `CK_LOG_MAX_AGE_DAYS` / `CK_LOG_ALARM_SEGMENT_MB`. This is the
264    /// zero-argument path the r2 spec requires so that reaching for the crate
265    /// costs no more than reaching for `eprintln!`.
266    #[cfg(feature = "store-paths")]
267    pub fn from_env() -> Result<Self, InitError> {
268        let module_id = env::var("SUBC_MODULE_ID")
269            .ok()
270            .filter(|value| !value.is_empty())
271            .ok_or(InitError::ModuleIdNotInEnvironment)?;
272        let mut config = Self::for_module(&module_id);
273        if let Some(days) = env_u32("CK_LOG_MAX_AGE_DAYS") {
274            config.retention.max_age_days = days;
275        }
276        if let Some(mb) = env_u32("CK_LOG_ALARM_SEGMENT_MB") {
277            config.retention.alarm_segment_mb = mb;
278        }
279        Ok(config)
280    }
281}
282
283#[cfg(feature = "store-paths")]
284fn env_u32(name: &str) -> Option<u32> {
285    env::var(name).ok()?.trim().parse().ok()
286}
287
288/// A live logger handle suitable for inclusion in module health reports.
289#[derive(Clone)]
290pub struct Handle {
291    inner: Arc<LoggerInner>,
292}
293
294impl Handle {
295    /// Returns the number of lines dropped after a write failure.
296    pub fn swallowed_writes(&self) -> u64 {
297        self.inner.swallowed_writes.load(Ordering::Relaxed)
298    }
299
300    /// Returns the segment path for the current instant.
301    pub fn path(&self) -> PathBuf {
302        self.inner.path_now()
303    }
304
305    /// The directory the segments live in.
306    pub fn logs_dir(&self) -> &Path {
307        &self.inner.logs_dir
308    }
309
310    /// Reports whether opening the directory failed and events are going to stderr.
311    pub fn fallback_active(&self) -> bool {
312        self.inner.fallback_active
313    }
314
315    /// Writes one line stamped with `at` into the segment `at` names, instead
316    /// of the one the logger's clock names now.
317    ///
318    /// For a record that must sit beside lines written under a different clock
319    /// reading. The case it exists for is a wall-clock step: the lines before
320    /// the step went to the segment the old clock named, so a marker describing
321    /// them belongs there too, stamped the way its neighbours are, or a reader
322    /// opening that file finds the lines and not the warning. Not level-filtered
323    /// (CK_LOG does not apply) and not for routine logging, which goes through
324    /// `tracing` so filtering and span context hold.
325    pub fn emit_at(
326        &self,
327        at: SystemTime,
328        level: tracing::Level,
329        logger: &str,
330        message: &str,
331        fields: &[(String, String)],
332    ) {
333        self.inner.emit_at(at, &level, logger, &[], message, fields);
334    }
335
336    /// [`Handle::emit_at`] with bound fields too, for a writer that renders on a
337    /// thread other than the one that produced the event (for example a queue
338    /// drained by a dedicated log thread). Such a writer cannot rely on the
339    /// caller's `tracing` span, so it carries the context itself: `bound` is
340    /// rendered in the bracket after the process-level fields, replacing a
341    /// process-level field of the same key. Not level-filtered (`CK_LOG` does
342    /// not apply); the producer decides what to enqueue.
343    pub fn emit_at_with_bound(
344        &self,
345        at: SystemTime,
346        level: tracing::Level,
347        logger: &str,
348        bound: &[(String, String)],
349        message: &str,
350        fields: &[(String, String)],
351    ) {
352        self.inner
353            .emit_at(at, &level, logger, bound, message, fields);
354    }
355
356    /// Installs the panic hook [`init`] installs: the panic text and a forced
357    /// backtrace go into the segment, one line each on logger
358    /// `<module>.panic`, and the previous hook still runs (the default one
359    /// prints to stderr). For a caller that composed the layer itself with
360    /// [`layer`] or [`layer_with_stderr_copy`]. Call it once; each call chains
361    /// another hook.
362    pub fn install_panic_hook(&self) {
363        install_panic_hook(Arc::clone(&self.inner));
364    }
365}
366
367// The handle of the logger `init` installed, so code that did not install it
368// (a library running inside a module's process) can still reach
369// `Handle::emit_at`. `init` can succeed only once per process, since the
370// tracing global can only be set once, so there is at most one to hold.
371static INSTALLED: OnceLock<Handle> = OnceLock::new();
372
373/// The logger this process installed with [`init`], if it installed one.
374pub fn installed() -> Option<Handle> {
375    INSTALLED.get().cloned()
376}
377
378/// An error that prevents installation of the global logger.
379#[derive(Clone, Debug, Eq, PartialEq)]
380pub enum InitError {
381    /// [`Config::from_env`] found no `SUBC_MODULE_ID`; the process is not a
382    /// daemon-spawned module and must name itself.
383    ModuleIdNotInEnvironment,
384    /// A process-global tracing subscriber was already installed.
385    GlobalSubscriberAlreadySet,
386}
387
388impl fmt::Display for InitError {
389    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
390        match self {
391            Self::ModuleIdNotInEnvironment => formatter.write_str(
392                "SUBC_MODULE_ID is not set; use Config::for_module(<id>) outside supervision",
393            ),
394            Self::GlobalSubscriberAlreadySet => {
395                formatter.write_str("a global tracing subscriber is already installed")
396            }
397        }
398    }
399}
400
401impl std::error::Error for InitError {}
402
403/// Installs the fleet logger as the process-global `tracing` subscriber.
404pub fn init(config: Config) -> Result<Handle, InitError> {
405    init_inner(config, None)
406}
407
408/// Installs the fleet logger with dependency crate labels and level controls.
409pub fn init_with_crates(config: Config, crates: Crates) -> Result<Handle, InitError> {
410    init_inner(config, Some(crates))
411}
412
413fn init_inner(config: Config, crates: Option<Crates>) -> Result<Handle, InitError> {
414    let (layer, handle) = build_layer(config, Box::new(io::stderr()), false, crates)?;
415    let panic_inner = Arc::clone(&handle.inner);
416    let subscriber = Registry::default().with(layer);
417    tracing::subscriber::set_global_default(subscriber)
418        .map_err(|_| InitError::GlobalSubscriberAlreadySet)?;
419    install_panic_hook(panic_inner);
420    let _ = INSTALLED.set(handle.clone());
421    Ok(handle)
422}
423
424/// The fleet layer without installing anything global, for a caller that
425/// composes its own `tracing` subscriber stack. Unlike [`init`], it installs no
426/// global subscriber and no panic hook ([`Handle::install_panic_hook`] does
427/// that), and [`installed`] does not return its handle.
428pub fn layer(config: Config) -> Result<(LogLayer, Handle), InitError> {
429    build_layer(config, Box::new(io::stderr()), false, None)
430}
431
432/// [`layer`] that also writes every rendered line to stderr after it reaches
433/// the segment. For a process whose stderr is watched by a person or a parent
434/// (a standalone bridge, a CLI), where the segment alone would hide its output.
435/// A supervised module should not use it: the daemon captures a module's stderr
436/// separately, so every line would be stored twice. When the segment directory
437/// cannot be opened, lines already go to stderr and are not doubled.
438pub fn layer_with_stderr_copy(config: Config) -> Result<(LogLayer, Handle), InitError> {
439    build_layer(config, Box::new(io::stderr()), true, None)
440}
441
442/// [`init`] with [`Config::from_env`]: the whole setup for a supervised module.
443#[cfg(feature = "store-paths")]
444pub fn init_from_env() -> Result<Handle, InitError> {
445    init(Config::from_env()?)
446}
447
448/// [`init_from_env`] with dependency crate labels and level controls.
449#[cfg(feature = "store-paths")]
450pub fn init_from_env_with_crates(crates: Crates) -> Result<Handle, InitError> {
451    init_with_crates(Config::from_env()?, crates)
452}
453
454/// Creates a span carrying canonical session lineage for nested events. Every
455/// event inside it renders `session=<issuer>:<id>` in the bound bracket.
456pub fn session_span(issuer: &str, id: &str) -> tracing::Span {
457    // An empty half means "no session": the line carries no field rather
458    // than a placeholder. Callers that used to log a synthetic id must pass
459    // nothing here instead; the crate does not know their sentinels.
460    if issuer.is_empty() || id.is_empty() {
461        tracing::Span::none()
462    } else {
463        let session = format!("{issuer}:{id}");
464        tracing::info_span!("cortexkit.session", session = %session)
465    }
466}
467
468/// Parses the fixed columns used by merged and filtered fleet log views.
469pub fn parse_line(line: &str) -> Result<ParsedLine<'_>, ParseError> {
470    format::parse(line)
471}
472
473struct LoggerInner {
474    module_id: String,
475    logs_dir: PathBuf,
476    process_bound: Vec<(String, String)>,
477    destination: Mutex<Option<SegmentDestination>>,
478    stderr: Mutex<Box<dyn Write + Send>>,
479    swallowed_writes: AtomicU64,
480    fallback_active: bool,
481    stderr_copy: bool,
482    redactor: Option<Arc<Redactor>>,
483    clock: Arc<dyn Fn() -> SystemTime + Send + Sync>,
484}
485
486impl LoggerInner {
487    fn path_now(&self) -> PathBuf {
488        self.logs_dir
489            .join(segment::segment_name(&self.module_id, (self.clock)()))
490    }
491
492    fn emit(
493        &self,
494        level: &tracing::Level,
495        logger: &str,
496        scoped_bound: &[(String, String)],
497        message: &str,
498        fields: &[(String, String)],
499    ) {
500        self.emit_at((self.clock)(), level, logger, scoped_bound, message, fields);
501    }
502
503    fn emit_at(
504        &self,
505        at: SystemTime,
506        level: &tracing::Level,
507        logger: &str,
508        scoped_bound: &[(String, String)],
509        message: &str,
510        fields: &[(String, String)],
511    ) {
512        // Process-level context first, then scoped: the process-level part is
513        // identical on every line the process writes, so putting it first keeps
514        // the bracket's leading columns stable within a file.
515        let mut bound: Vec<(String, String)> = self.process_bound.clone();
516        for (key, value) in scoped_bound {
517            match bound.iter_mut().find(|(existing, _)| existing == key) {
518                Some(slot) => slot.1 = value.clone(),
519                None => bound.push((key.clone(), value.clone())),
520            }
521        }
522        let raw = format::render_line(at, level, logger, &bound, message, fields);
523        let fleet_redacted = fleet_redact(&raw);
524        let module_redacted = self.redactor.as_ref().map_or_else(
525            || Cow::Borrowed(fleet_redacted.as_ref()),
526            |redactor| redactor(&fleet_redacted),
527        );
528        // Redactors are extensibility points, so the final guard preserves the
529        // one-line, no-raw-control contract even if a module redactor introduces
530        // such bytes. It escapes rather than strips, because a strip can consume
531        // text the redactor never meant to touch.
532        let guarded = format::escape_raw_controls(&module_redacted);
533        self.write_line(&guarded, at);
534    }
535
536    fn write_line(&self, line: &str, at: SystemTime) {
537        let mut bytes = Vec::with_capacity(line.len() + 1);
538        bytes.extend_from_slice(line.as_bytes());
539        bytes.push(b'\n');
540
541        // The mutex keeps this process's lines whole against its own threads;
542        // O_APPEND keeps them whole against other processes. No queue, no
543        // background flusher: a caller waits only for the write in front of it.
544        let result = {
545            let mut destination = self
546                .destination
547                .lock()
548                .unwrap_or_else(std::sync::PoisonError::into_inner);
549            match destination.as_mut() {
550                None => {
551                    let mut stderr = self
552                        .stderr
553                        .lock()
554                        .unwrap_or_else(std::sync::PoisonError::into_inner);
555                    stderr.write_all(&bytes).map(|()| None)
556                }
557                Some(segment) => {
558                    let written = segment.write(&bytes, at);
559                    if self.stderr_copy && written.is_ok() {
560                        let mut stderr = self
561                            .stderr
562                            .lock()
563                            .unwrap_or_else(std::sync::PoisonError::into_inner);
564                        let _ = stderr.write_all(&bytes);
565                    }
566                    written
567                }
568            }
569        };
570
571        match result {
572            Ok(None) => {}
573            Ok(Some(notice)) => self.report_notice(notice),
574            Err(error) => {
575                self.swallowed_writes.fetch_add(1, Ordering::Relaxed);
576                if !WRITE_FAILURE_REPORTED.swap(true, Ordering::Relaxed) {
577                    self.report(&format!(
578                        "cortexkit-log: log write failed; future failures will be swallowed: {error}\n"
579                    ));
580                }
581            }
582        }
583    }
584
585    // A feature that fires later must say that it fired: without these lines,
586    // "retention never ran" and "ran and found nothing to prune" are the same
587    // observation from outside. Oversize is reported once per process because
588    // a runaway writer must not get a second flood from its own alarm.
589    fn report_notice(&self, notice: SegmentNotice) {
590        match notice {
591            SegmentNotice::Pruned { removed, kept } => self.report(&format!(
592                "cortexkit-log: {}.retention pruned={removed} kept={kept}\n",
593                self.module_id
594            )),
595            SegmentNotice::Oversized { path, bytes } => self.report(&format!(
596                "cortexkit-log: segment oversized, NOT truncated: path={} bytes={bytes}\n",
597                path.display()
598            )),
599        }
600    }
601
602    fn report(&self, report: &str) {
603        let mut stderr = self
604            .stderr
605            .lock()
606            .unwrap_or_else(std::sync::PoisonError::into_inner);
607        let _ = stderr.write_all(report.as_bytes());
608    }
609
610    fn write_panic(&self, information: &panic::PanicHookInfo<'_>) {
611        let at = (self.clock)();
612        let logger = format!("{}.panic", self.module_id);
613        let panic_text = information.to_string();
614        for line in panic_text.lines() {
615            self.emit_at(at, &tracing::Level::ERROR, &logger, &[], line, &[]);
616        }
617        let backtrace = Backtrace::force_capture().to_string();
618        for line in backtrace.lines() {
619            self.emit_at(at, &tracing::Level::ERROR, &logger, &[], line, &[]);
620        }
621    }
622}
623
624/// The fleet `tracing` layer, built by [`layer`] or [`layer_with_stderr_copy`]
625/// for a caller that installs its own subscriber.
626pub struct LogLayer {
627    inner: Arc<LoggerInner>,
628    filter: CkLogFilter,
629    crates: Option<Crates>,
630}
631
632impl LogLayer {
633    /// Adds dependency crate labels and level controls to an existing layer.
634    ///
635    /// This is available for layers created by either [`layer`] or
636    /// [`layer_with_stderr_copy`].
637    pub fn with_crates(mut self, crates: Crates) -> Self {
638        self.crates = Some(crates);
639        self
640    }
641
642    fn event_path<'a>(&self, metadata: &'a Metadata<'_>) -> format::LoggerPath<'a> {
643        let Some(crates) = &self.crates else {
644            return format::LoggerPath::from_target(&self.inner.module_id, metadata.target());
645        };
646
647        let module_path = metadata.module_path().unwrap_or(metadata.target());
648        let crate_name = module_path.split("::").next().unwrap_or(module_path);
649        if crates.own.contains(crate_name) {
650            return format::LoggerPath::from_target(&self.inner.module_id, metadata.target());
651        }
652
653        format::LoggerPath::dependency(crate_name)
654    }
655
656    fn metadata_enabled(&self, metadata: &Metadata<'_>) -> bool {
657        if metadata.is_span() {
658            return true;
659        }
660        let path = self.event_path(metadata);
661        self.event_enabled(metadata, path)
662    }
663
664    fn event_enabled(&self, metadata: &Metadata<'_>, path: format::LoggerPath<'_>) -> bool {
665        let ceiling = self.crates.as_ref().and_then(|crates| {
666            crates.ceiling_for(
667                metadata.module_path().unwrap_or(metadata.target()),
668                path.dependency_name().is_some(),
669            )
670        });
671        self.filter
672            .enabled_path(&self.inner.module_id, path, metadata.level(), ceiling)
673    }
674}
675
676impl<S> Layer<S> for LogLayer
677where
678    S: Subscriber + for<'lookup> LookupSpan<'lookup>,
679{
680    fn register_callsite(
681        &self,
682        metadata: &'static Metadata<'static>,
683    ) -> tracing::subscriber::Interest {
684        if !metadata.is_event() || self.metadata_enabled(metadata) {
685            tracing::subscriber::Interest::always()
686        } else {
687            tracing::subscriber::Interest::never()
688        }
689    }
690
691    fn max_level_hint(&self) -> Option<LevelFilter> {
692        let own_crates_possible = self
693            .crates
694            .as_ref()
695            .is_none_or(|crates| !crates.own.is_empty());
696        let level = self.filter.max_level_hint(
697            &self.inner.module_id,
698            own_crates_possible,
699            self.crates.as_ref().map(|crates| &crates.ceilings),
700        );
701        Some(level.map_or(LevelFilter::OFF, LevelFilter::from_level))
702    }
703
704    fn enabled(&self, metadata: &Metadata<'_>, _context: Context<'_, S>) -> bool {
705        self.metadata_enabled(metadata)
706    }
707
708    fn on_new_span(&self, attributes: &Attributes<'_>, id: &Id, context: Context<'_, S>) {
709        let mut visitor = BoundVisitor::default();
710        attributes.record(&mut visitor);
711        if let (false, Some(span)) = (visitor.bound.is_empty(), context.span(id)) {
712            span.extensions_mut().insert(SpanBound(visitor.bound));
713        }
714    }
715
716    fn on_record(&self, id: &Id, values: &Record<'_>, context: Context<'_, S>) {
717        let mut visitor = BoundVisitor::default();
718        values.record(&mut visitor);
719        if let (false, Some(span)) = (visitor.bound.is_empty(), context.span(id)) {
720            let mut extensions = span.extensions_mut();
721            match extensions.get_mut::<SpanBound>() {
722                Some(existing) => existing.0.extend(visitor.bound),
723                None => extensions.insert(SpanBound(visitor.bound)),
724            }
725        }
726    }
727
728    fn on_event(&self, event: &Event<'_>, context: Context<'_, S>) {
729        let metadata = event.metadata();
730        let path = self.event_path(metadata);
731        if !self.event_enabled(metadata, path) {
732            return;
733        }
734        let logger = path.logger_name(&self.inner.module_id);
735
736        let mut visitor = EventVisitor::default();
737        event.record(&mut visitor);
738        // Every field on every span enclosing the event is bound context,
739        // root-first so an inner span overrides an outer one with the same key.
740        // This is MDC: the module decides what is in scope by what it puts on
741        // its spans, and the crate renders whatever is there.
742        let mut scoped: Vec<(String, String)> = Vec::new();
743        if let Some(scope) = context.event_scope(event) {
744            for span in scope.from_root() {
745                if let Some(bound) = span.extensions().get::<SpanBound>() {
746                    for (key, value) in &bound.0 {
747                        match scoped.iter_mut().find(|(existing, _)| existing == key) {
748                            Some(slot) => slot.1 = value.clone(),
749                            None => scoped.push((key.clone(), value.clone())),
750                        }
751                    }
752                }
753            }
754        }
755        self.inner.emit(
756            metadata.level(),
757            &logger,
758            &scoped,
759            visitor.message.as_deref().unwrap_or(""),
760            &visitor.fields,
761        );
762    }
763}
764
765#[derive(Clone)]
766struct SpanBound(Vec<(String, String)>);
767
768#[derive(Default)]
769struct BoundVisitor {
770    bound: Vec<(String, String)>,
771}
772
773impl BoundVisitor {
774    fn record(&mut self, field: &Field, value: String) {
775        // An empty value binds nothing: `session_span("", "")` and a plugin
776        // with no harness must produce a line with no bracket, never `key=`.
777        if !value.is_empty() {
778            self.bound.push((field.name().to_owned(), value));
779        }
780    }
781}
782
783impl Visit for BoundVisitor {
784    fn record_str(&mut self, field: &Field, value: &str) {
785        self.record(field, value.to_owned());
786    }
787
788    fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
789        let rendered = format!("{value:?}");
790        let value = rendered
791            .strip_prefix('"')
792            .and_then(|unquoted| unquoted.strip_suffix('"'))
793            .unwrap_or(&rendered);
794        self.record(field, value.to_owned());
795    }
796
797    fn record_i64(&mut self, field: &Field, value: i64) {
798        self.record(field, value.to_string());
799    }
800
801    fn record_u64(&mut self, field: &Field, value: u64) {
802        self.record(field, value.to_string());
803    }
804
805    fn record_bool(&mut self, field: &Field, value: bool) {
806        self.record(field, value.to_string());
807    }
808}
809
810#[derive(Default)]
811struct EventVisitor {
812    message: Option<String>,
813    fields: Vec<(String, String)>,
814}
815
816impl EventVisitor {
817    fn record(&mut self, field: &Field, value: String) {
818        if field.name() == "message" {
819            self.message = Some(value);
820        } else {
821            self.fields.push((field.name().to_owned(), value));
822        }
823    }
824}
825
826impl Visit for EventVisitor {
827    fn record_f64(&mut self, field: &Field, value: f64) {
828        self.record(field, value.to_string());
829    }
830
831    fn record_i64(&mut self, field: &Field, value: i64) {
832        self.record(field, value.to_string());
833    }
834
835    fn record_u64(&mut self, field: &Field, value: u64) {
836        self.record(field, value.to_string());
837    }
838
839    fn record_i128(&mut self, field: &Field, value: i128) {
840        self.record(field, value.to_string());
841    }
842
843    fn record_u128(&mut self, field: &Field, value: u128) {
844        self.record(field, value.to_string());
845    }
846
847    fn record_bool(&mut self, field: &Field, value: bool) {
848        self.record(field, value.to_string());
849    }
850
851    fn record_str(&mut self, field: &Field, value: &str) {
852        self.record(field, value.to_owned());
853    }
854
855    fn record_error(&mut self, field: &Field, value: &(dyn std::error::Error + 'static)) {
856        self.record(field, value.to_string());
857    }
858
859    fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
860        self.record(field, format!("{value:?}"));
861    }
862}
863
864fn build_layer(
865    config: Config,
866    stderr: Box<dyn Write + Send>,
867    stderr_copy: bool,
868    crates: Option<Crates>,
869) -> Result<(LogLayer, Handle), InitError> {
870    let clock = config.clock.unwrap_or_else(|| Arc::new(SystemTime::now));
871    let now = clock();
872    let (destination, open_notice, open_error) = match SegmentDestination::open(
873        &config.logs_dir,
874        &config.module_id,
875        config.retention,
876        now,
877        true,
878    ) {
879        Ok((destination, notice)) => (Some(destination), notice, None),
880        Err(error) => (None, None, Some(error)),
881    };
882    let fallback_active = open_error.is_some();
883    let inner = Arc::new(LoggerInner {
884        module_id: config.module_id,
885        logs_dir: config.logs_dir,
886        process_bound: config.bound,
887        destination: Mutex::new(destination),
888        stderr: Mutex::new(stderr),
889        swallowed_writes: AtomicU64::new(0),
890        fallback_active,
891        stderr_copy,
892        redactor: config.redactor,
893        clock,
894    });
895
896    if let Some(notice) = open_notice {
897        inner.report_notice(notice);
898    }
899    if let Some(error) = open_error {
900        let logger = inner.module_id.clone();
901        inner.emit(
902            &tracing::Level::ERROR,
903            &logger,
904            &[],
905            "log directory unavailable; falling back to stderr",
906            &[
907                ("dir".to_owned(), inner.logs_dir.display().to_string()),
908                ("error".to_owned(), error.to_string()),
909            ],
910        );
911    }
912
913    let filter = make_filter(config.spec, &inner);
914    let layer = LogLayer {
915        inner: Arc::clone(&inner),
916        filter,
917        crates,
918    };
919    Ok((layer, Handle { inner }))
920}
921
922fn make_filter(spec_override: Option<String>, inner: &LoggerInner) -> CkLogFilter {
923    let spec = spec_override.or_else(|| env::var("CK_LOG").ok());
924    let spec = spec
925        .as_deref()
926        .map(str::trim)
927        .filter(|value| !value.is_empty());
928    match spec {
929        Some(spec) => CkLogFilter::parse(spec).unwrap_or_else(|error| {
930            if !FILTER_FAILURE_REPORTED.swap(true, Ordering::Relaxed) {
931                inner.report(&format!(
932                    "cortexkit-log: invalid CK_LOG value {spec:?}; using info: {error}\n"
933                ));
934            }
935            CkLogFilter::info()
936        }),
937        None => CkLogFilter::info(),
938    }
939}
940
941fn install_panic_hook(inner: Arc<LoggerInner>) {
942    let previous = panic::take_hook();
943    panic::set_hook(Box::new(move |information| {
944        inner.write_panic(information);
945        previous(information);
946    }));
947}
948
949#[cfg(test)]
950mod tests;