Skip to main content

lean_ctx/core/
logging.rs

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