Skip to main content

lean_ctx_ext/core/
logging.rs

1// SPDX-License-Identifier: Apache-2.0
2use std::io::IsTerminal;
3
4use tracing::Level;
5use tracing_subscriber::EnvFilter;
6use tracing_subscriber::layer::SubscriberExt;
7use tracing_subscriber::util::SubscriberInitExt;
8
9/// Initialize the tracing subscriber for a server-like command (daemon,
10/// proxy, serve, …) that is not the stdio MCP server.
11///
12/// Respects `LEAN_CTX_LOG` and `RUST_LOG` environment variables for filter control.
13/// Defaults to `warn` level.
14pub fn init_logging() {
15    init_with_default(default_level(true));
16}
17
18/// Initialize the tracing subscriber for a user-facing command. Defaults
19/// to `error`: what a person needs to know is printed as a plain line by
20/// the command itself, not as a `WARN` log record. `LEAN_CTX_LOG` /
21/// `RUST_LOG` still raise it.
22pub fn init_cli_logging() {
23    init_with_default(default_level(false));
24}
25
26/// The default filter when neither `LEAN_CTX_LOG` nor `RUST_LOG` is set:
27/// `warn` for server-like processes, `error` for user-facing commands.
28pub fn default_level(server_mode: bool) -> &'static str {
29    if server_mode { "warn" } else { "error" }
30}
31
32/// Initialize logging for daemon/MCP mode (stderr, defaults to `info`).
33/// Daemon logs go to a file, so verbosity is fine.
34pub fn init_mcp_logging() {
35    init_with_default("info");
36}
37
38/// The one place a subscriber is installed, for every process mode (CLI,
39/// stdio MCP server, HTTP/streamable server, daemon, proxy).
40///
41/// Two filters apply, and an event has to pass BOTH:
42///
43/// 1. the directives from `LEAN_CTX_LOG` / `RUST_LOG` (or `default`), as
44///    before;
45/// 2. [`carries_no_request_payload`], installed as a second layer on top.
46///
47/// The second is not a directive inside the first, so nothing in the
48/// environment can lift it: an `EnvFilter` picks the most specific matching
49/// directive (`rmcp::service=trace` would beat a later `rmcp=info`), while a
50/// layer's `enabled` is combined with the layers below it by AND.
51fn init_with_default(default: &str) {
52    let filter = std::env::var("LEAN_CTX_LOG")
53        .or_else(|_| std::env::var("RUST_LOG"))
54        .unwrap_or_else(|_| default.to_string());
55
56    let _ = tracing_subscriber::fmt()
57        .with_env_filter(EnvFilter::new(filter))
58        .with_writer(std::io::stderr)
59        .with_ansi(stderr_is_terminal())
60        .finish()
61        .with(tracing_subscriber::filter::filter_fn(|metadata| {
62            carries_no_request_payload(metadata.target(), *metadata.level())
63        }))
64        .try_init();
65}
66
67/// Whether an event of `target` at `level` may be emitted at all.
68///
69/// The MCP library logs whole inbound messages below `INFO`
70/// (`rmcp::service`: "received request" with the request; the streamable
71/// HTTP transport: every message). A request carries the host's `_meta`,
72/// which may hold a presenter capability
73/// (`server::call_identity`), and tool arguments. So every `rmcp` target is
74/// capped at `INFO`, unconditionally.
75///
76/// Cost, accepted: `rmcp` debug and trace logs are not available in any
77/// lean-ctx process, whatever `RUST_LOG` says.
78fn carries_no_request_payload(target: &str, level: Level) -> bool {
79    let rmcp = target == "rmcp" || target.starts_with("rmcp::");
80    !rmcp || level <= Level::INFO
81}
82
83/// Colour escapes only for a person at a terminal: redirected to a file or
84/// captured into an agent's tool result they are noise (#1866).
85fn stderr_is_terminal() -> bool {
86    std::io::stderr().is_terminal()
87}
88
89#[cfg(test)]
90mod tests {
91    use super::{Level, carries_no_request_payload};
92
93    /// The cap is a predicate of its own, applied on top of whatever the
94    /// environment asks for: for `rmcp::service` (and every other `rmcp`
95    /// target) nothing more verbose than `INFO` passes, so the effective
96    /// maximum is `INFO` under `RUST_LOG=trace` too. Other targets are not
97    /// touched.
98    #[test]
99    fn rmcp_targets_are_capped_at_info_whatever_the_environment_says() {
100        for target in [
101            "rmcp",
102            "rmcp::service",
103            "rmcp::transport::streamable_http_server::tower",
104        ] {
105            for passes in [Level::ERROR, Level::WARN, Level::INFO] {
106                assert!(carries_no_request_payload(target, passes), "{target}");
107            }
108            for capped in [Level::DEBUG, Level::TRACE] {
109                assert!(!carries_no_request_payload(target, capped), "{target}");
110            }
111        }
112        for other in ["lean_ctx::server", "rmcpx", "hyper"] {
113            assert!(carries_no_request_payload(other, Level::TRACE), "{other}");
114        }
115    }
116}