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