Skip to main content

docsrs_cli/
diagnostics.rs

1//! Process-local diagnostic subscriber for the CLI entry path.
2//!
3//! # Binary vs library
4//!
5//! Product modules (`http`, `cache`, `docs_rs`, …) only **emit** events/spans.
6//! Global subscriber installation happens once on the process entry path
7//! ([`crate::run`] / [`crate::run_with_io`]), not from pure library helpers.
8//!
9//! # Agent-first sinks
10//!
11//! - **stdout**: structured command output (JSON/Markdown) — never diagnostics
12//! - **stderr**: tracing events, progress lines, human errors
13//!
14//! File rotation (`tracing-appender`), OpenTelemetry/OTLP, `reload::Layer` admin
15//! endpoints, and `tokio-console` are **out of scope** for this one-shot CLI:
16//! there is no long-lived process, no admin surface, and no product telemetry
17//! export. Diagnostics stay on stderr for agent capture.
18//!
19//! # Targets
20//!
21//! Events use module paths under `docsrs_cli::…` (e.g. `docsrs_cli::http`,
22//! `docsrs_cli::cache`, `docsrs_cli::diagnostics`). Steer them with `-v` / `-q`
23//! or with the XDG key `log_directive`
24//! (e.g. `log_directive = "docsrs_cli=debug,docsrs_cli::http=trace"`).
25//!
26//! # No product environment variable
27//!
28//! The filter is built from CLI flags and `config.toml` only. `RUST_LOG` is
29//! **not** read (ADR 0009).
30//!
31//! This module used to call `EnvFilter::try_from_default_env()`, which let
32//! `RUST_LOG` override `-q` — an ambient value silently outranking an explicit
33//! flag. The practical harm is not the rule violation: it made the product
34//! unconfigurable *by the product*, because no `docsrs-cli` command could turn
35//! that stderr noise off, while `doctor` kept reporting `(no env)`.
36//!
37//! Terminal-capability variables (`NO_COLOR`, `TERM`, `CLICOLOR_FORCE`) are a
38//! different category and stay: they describe the *device*, like `isatty`, and
39//! never carry product configuration. See [`crate::platform`].
40
41use std::io;
42
43use tracing_subscriber::EnvFilter;
44use tracing_subscriber::layer::SubscriberExt;
45use tracing_subscriber::util::SubscriberInitExt;
46
47use crate::cli::Cli;
48use crate::config::DEFAULT_LOG_DIRECTIVE;
49
50/// Install the global `tracing` subscriber once for this process.
51///
52/// Writes to **stderr** with an `EnvFilter` built from CLI verbosity and the
53/// XDG `log_directive` key — never from the environment. Idempotent: a second
54/// call (integration tests re-enter `run_with_io`) is a no-op so the first
55/// install wins for the process lifetime.
56///
57/// `toml_directive` comes from `config.toml`; an unparseable value falls back to
58/// [`DEFAULT_LOG_DIRECTIVE`] instead of aborting, because a typo in an optional
59/// diagnostics knob must never take the command down with it.
60///
61/// Does **not** return a `WorkerGuard`: the writer is stderr (no background
62/// appender thread). FINALIZE still flushes stdio via [`crate::shutdown::flush_stdio`].
63pub fn init_tracing(cli: &Cli, toml_directive: Option<&str>) {
64    let directive = resolve_directive(cli, toml_directive);
65    let filter =
66        EnvFilter::try_new(directive).unwrap_or_else(|_| EnvFilter::new(DEFAULT_LOG_DIRECTIVE));
67    let filter_display = filter.to_string();
68    // Color policy: --no-color, NO_COLOR, TERM=dumb, CLICOLOR_FORCE (see platform).
69    let ansi = crate::platform::ansi_colors_enabled(cli.no_color);
70
71    // Registry + fmt layer: composable base; log crate bridge via feature
72    // `tracing-log` on tracing-subscriber (reqwest/html5ever emit via `log`).
73    let fmt_layer = tracing_subscriber::fmt::layer()
74        .with_writer(io::stderr)
75        .with_ansi(ansi)
76        .with_target(true)
77        .with_level(true)
78        .with_thread_ids(false)
79        .with_thread_names(false);
80
81    let result = tracing_subscriber::registry()
82        .with(filter)
83        .with(fmt_layer)
84        .try_init();
85
86    match result {
87        Ok(()) => {
88            tracing::debug!(
89                target: "docsrs_cli::diagnostics",
90                filter = %filter_display,
91                ansi,
92                "tracing subscriber installed (stderr diagnostics)"
93            );
94        }
95        Err(_) => {
96            // Already installed in this process (tests call run_with_io many times).
97            // Do not panic; first successful install owns the global default.
98        }
99    }
100}
101
102/// Resolve the effective filter directive: CLI flags, then TOML, then default.
103///
104/// An explicit `-q` / `-v` always outranks `config.toml`, so the flag the
105/// operator typed in this invocation wins over the file they wrote once.
106pub(crate) fn resolve_directive<'a>(cli: &Cli, toml_directive: Option<&'a str>) -> &'a str {
107    if let Some(explicit) = cli_directive(cli) {
108        return explicit;
109    }
110    toml_directive
111        .map(str::trim)
112        .filter(|d| !d.is_empty())
113        .unwrap_or(DEFAULT_LOG_DIRECTIVE)
114}
115
116/// Directive demanded by `-q` / `-v`, or `None` when neither was passed.
117///
118/// Returning `None` (not the default) is what lets `log_directive` apply: a
119/// default folded in here would be indistinguishable from an explicit request
120/// and would silently outrank the file.
121fn cli_directive(cli: &Cli) -> Option<&'static str> {
122    if cli.quiet {
123        Some("error")
124    } else if cli.verbose >= 2 {
125        Some("trace")
126    } else if cli.verbose == 1 {
127        Some("debug")
128    } else {
129        None
130    }
131}
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136    use crate::cli::{Cli, Commands};
137    use clap::Parser;
138
139    fn cli_with(args: &[&str]) -> Cli {
140        Cli::try_parse_from(args).expect("parse test argv")
141    }
142
143    #[test]
144    fn no_flags_and_no_toml_key_is_error() {
145        let cli = cli_with(&["docsrs-cli", "version"]);
146        assert_eq!(resolve_directive(&cli, None), "error");
147    }
148
149    #[test]
150    fn verbose_maps_to_debug_and_trace() {
151        let v1 = cli_with(&["docsrs-cli", "-v", "version"]);
152        assert_eq!(resolve_directive(&v1, None), "debug");
153        let v2 = cli_with(&["docsrs-cli", "-vv", "version"]);
154        assert_eq!(resolve_directive(&v2, None), "trace");
155    }
156
157    #[test]
158    fn quiet_wins_over_verbose() {
159        let cli = cli_with(&["docsrs-cli", "-q", "-vv", "version"]);
160        assert_eq!(resolve_directive(&cli, None), "error");
161        let _ = cli.command;
162    }
163
164    #[test]
165    fn init_tracing_is_idempotent() {
166        let cli = cli_with(&["docsrs-cli", "version"]);
167        init_tracing(&cli, None);
168        init_tracing(&cli, None);
169        // Second call must not panic; command still parseable.
170        assert!(matches!(cli.command, Commands::Version));
171    }
172
173    #[test]
174    fn toml_directive_applies_only_without_explicit_flags() {
175        // GAP-ENV-001: the XDG key replaces `RUST_LOG`, so it must behave the way
176        // a config file should — yielding to the flag typed in this invocation.
177        let bare = cli_with(&["docsrs-cli", "version"]);
178        assert_eq!(
179            resolve_directive(&bare, Some("docsrs_cli=debug")),
180            "docsrs_cli=debug"
181        );
182
183        let quiet = cli_with(&["docsrs-cli", "-q", "version"]);
184        assert_eq!(resolve_directive(&quiet, Some("docsrs_cli=trace")), "error");
185
186        let verbose = cli_with(&["docsrs-cli", "-v", "version"]);
187        assert_eq!(
188            resolve_directive(&verbose, Some("docsrs_cli=trace")),
189            "debug"
190        );
191    }
192
193    #[test]
194    fn blank_toml_directive_falls_back_to_default() {
195        // A key present but empty is an operator typo, not a request for silence
196        // of an unparseable kind; treat it as absent rather than as a directive.
197        let cli = cli_with(&["docsrs-cli", "version"]);
198        assert_eq!(resolve_directive(&cli, Some("   ")), DEFAULT_LOG_DIRECTIVE);
199        assert_eq!(resolve_directive(&cli, None), DEFAULT_LOG_DIRECTIVE);
200    }
201}