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`). Override with `RUST_LOG`
23//! (e.g. `RUST_LOG=docsrs_cli=debug,docsrs_cli::http=trace`).
24//!
25//! # CLI vs env
26//!
27//! `-v` / `-vv` / `-q` set the default directive when `RUST_LOG` is unset.
28//! When `RUST_LOG` is set, it wins over CLI verbosity (standard EnvFilter).
29
30use std::io;
31
32use tracing_subscriber::EnvFilter;
33use tracing_subscriber::layer::SubscriberExt;
34use tracing_subscriber::util::SubscriberInitExt;
35
36use crate::cli::Cli;
37
38/// Install the global `tracing` subscriber once for this process.
39///
40/// Writes to **stderr** with `EnvFilter` from `RUST_LOG` or CLI verbosity.
41/// Idempotent: a second call (integration tests re-enter `run_with_io`) is a
42/// no-op so the first install wins for the process lifetime.
43///
44/// Does **not** return a `WorkerGuard`: the writer is stderr (no background
45/// appender thread). FINALIZE still flushes stdio via [`crate::shutdown::flush_stdio`].
46pub fn init_tracing(cli: &Cli) {
47    let default_level = default_directive(cli);
48    let filter =
49        EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(default_level));
50    let filter_display = filter.to_string();
51    // Color policy: --no-color, NO_COLOR, TERM=dumb, CLICOLOR_FORCE (see platform).
52    let ansi = crate::platform::ansi_colors_enabled(cli.no_color);
53
54    // Registry + fmt layer: composable base; log crate bridge via feature
55    // `tracing-log` on tracing-subscriber (reqwest/html5ever emit via `log`).
56    let fmt_layer = tracing_subscriber::fmt::layer()
57        .with_writer(io::stderr)
58        .with_ansi(ansi)
59        .with_target(true)
60        .with_level(true)
61        .with_thread_ids(false)
62        .with_thread_names(false);
63
64    let result = tracing_subscriber::registry()
65        .with(filter)
66        .with(fmt_layer)
67        .try_init();
68
69    match result {
70        Ok(()) => {
71            tracing::debug!(
72                target: "docsrs_cli::diagnostics",
73                filter = %filter_display,
74                default_level,
75                ansi,
76                "tracing subscriber installed (stderr diagnostics)"
77            );
78        }
79        Err(_) => {
80            // Already installed in this process (tests call run_with_io many times).
81            // Do not panic; first successful install owns the global default.
82        }
83    }
84}
85
86/// Default EnvFilter directive from `-q` / `-v` when `RUST_LOG` is unset.
87///
88/// Agent-first default is `error` (quiet stderr unless the operator asks).
89pub(crate) fn default_directive(cli: &Cli) -> &'static str {
90    if cli.quiet {
91        "error"
92    } else if cli.verbose >= 2 {
93        "trace"
94    } else if cli.verbose == 1 {
95        "debug"
96    } else {
97        "error"
98    }
99}
100
101#[cfg(test)]
102mod tests {
103    use super::*;
104    use crate::cli::{Cli, Commands};
105    use clap::Parser;
106
107    fn cli_with(args: &[&str]) -> Cli {
108        Cli::try_parse_from(args).expect("parse test argv")
109    }
110
111    #[test]
112    fn default_directive_agent_first_is_error() {
113        let cli = cli_with(&["docsrs-cli", "version"]);
114        assert_eq!(default_directive(&cli), "error");
115    }
116
117    #[test]
118    fn default_directive_verbose_debug_and_trace() {
119        let v1 = cli_with(&["docsrs-cli", "-v", "version"]);
120        assert_eq!(default_directive(&v1), "debug");
121        let v2 = cli_with(&["docsrs-cli", "-vv", "version"]);
122        assert_eq!(default_directive(&v2), "trace");
123    }
124
125    #[test]
126    fn default_directive_quiet_wins_over_verbose() {
127        let cli = cli_with(&["docsrs-cli", "-q", "-vv", "version"]);
128        assert_eq!(default_directive(&cli), "error");
129        let _ = cli.command;
130    }
131
132    #[test]
133    fn init_tracing_is_idempotent() {
134        let cli = cli_with(&["docsrs-cli", "version"]);
135        init_tracing(&cli);
136        init_tracing(&cli);
137        // Second call must not panic; command still parseable.
138        assert!(matches!(cli.command, Commands::Version));
139    }
140}