Skip to main content

sqlserver_mcp_catalog/core/
logger.rs

1// SQL Server - master/msdb/sandbox combined catalog MCP server — generated by mcpify. Do not hand-edit.
2
3use tracing_subscriber::Registry;
4use tracing_subscriber::fmt::writer::BoxMakeWriter;
5use tracing_subscriber::layer::SubscriberExt;
6use tracing_subscriber::util::SubscriberInitExt;
7use tracing_subscriber::{EnvFilter, Layer, fmt};
8
9use super::log_transport::use_pretty_output;
10
11const LOG_LEVEL_ENV_VAR: &str = "SQLSERVER_LOG_LEVEL";
12const TRANSPORT_ENV_VAR: &str = "SQLSERVER_TRANSPORT";
13
14/// A type-erased `tracing_subscriber` layer — lets `otel::build_layer`'s
15/// OpenTelemetry bridge layer compose into the same subscriber
16/// `init_logging` installs, without `init_logging` needing to name
17/// `otel`'s concrete layer type.
18pub type BoxedLayer = Box<dyn Layer<Registry> + Send + Sync>;
19
20/// `SQLSERVER_LOG_LEVEL`, defaulting to `"info"` when unset.
21pub fn resolve_log_level() -> String {
22    std::env::var(LOG_LEVEL_ENV_VAR).unwrap_or_else(|_| "info".to_string())
23}
24
25/// `true` when the active transport is HTTP, in which case stdout carries
26/// no protocol traffic and logs go there instead of stderr — see
27/// `init_logging`.
28pub fn logs_to_stdout() -> bool {
29    std::env::var(TRANSPORT_ENV_VAR).as_deref() == Ok("http")
30}
31
32/// Installs the process-global structured logger: JSON output (pretty on an
33/// interactive TTY), level from `resolve_log_level()` — mirrors
34/// `targets::typescript`'s `logger.ts`. Correlation IDs are carried as a
35/// `trace_id` span field (see `correlation_context`) rather than pino's
36/// per-record `mixin`, since `tracing` spans are the idiomatic Rust
37/// equivalent of that pattern. Field-level secret redaction isn't automatic
38/// here; call `sanitizer::sanitize` before logging any user- or
39/// API-controlled JSON payload.
40///
41/// `otel_layer` is composed into the same subscriber when tracing export is
42/// enabled (see `otel::build_layer`), since `tracing` only allows a single
43/// global default subscriber — the two layers can't be installed
44/// independently without one call overwriting the other. Call once, at
45/// process startup.
46pub fn init_logging(otel_layer: Option<BoxedLayer>) {
47    let filter = EnvFilter::try_new(resolve_log_level()).unwrap_or_else(|_| EnvFilter::new("info"));
48    // The MCP stdio transport (see `mcp_server::connect_stdio`) speaks
49    // JSON-RPC over stdout — any other writer sharing that stream
50    // (tracing's default) corrupts every frame parsed on the client side.
51    // Logs go to stderr in stdio mode; in HTTP mode stdout carries no
52    // protocol traffic, so logs go there instead (see `logs_to_stdout`).
53    let writer: BoxMakeWriter = if logs_to_stdout() {
54        BoxMakeWriter::new(std::io::stdout)
55    } else {
56        BoxMakeWriter::new(std::io::stderr)
57    };
58    let fmt_layer: BoxedLayer = if use_pretty_output() {
59        fmt::layer().pretty().with_writer(writer).boxed()
60    } else {
61        fmt::layer().json().with_writer(writer).boxed()
62    };
63
64    // `fmt_layer`/`otel_layer` are boxed as `Layer<Registry>` specifically,
65    // so they must land directly on the bare `registry()` (a single
66    // `Vec<BoxedLayer>` `.with()` call, since `Vec<L>` itself implements
67    // `Layer<S>`) before anything — including the filter — changes the
68    // accumulated subscriber's type; `EnvFilter` implements `Layer<S>`
69    // generically for any `S`, so it can compose on top afterward.
70    let layers: Vec<BoxedLayer> = std::iter::once(fmt_layer).chain(otel_layer).collect();
71
72    tracing_subscriber::registry()
73        .with(layers)
74        .with(filter)
75        .init();
76}
77
78#[cfg(test)]
79mod tests {
80    use super::*;
81
82    #[test]
83    fn defaults_to_info_when_env_var_unset() {
84        // SAFETY: test-only env mutation, single-threaded within this test.
85        unsafe {
86            std::env::remove_var(LOG_LEVEL_ENV_VAR);
87        }
88        assert_eq!(resolve_log_level(), "info");
89    }
90
91    #[test]
92    fn reads_the_configured_level_from_the_env_var() {
93        // SAFETY: test-only env mutation, single-threaded within this test.
94        unsafe {
95            std::env::set_var(LOG_LEVEL_ENV_VAR, "debug");
96        }
97        assert_eq!(resolve_log_level(), "debug");
98        unsafe {
99            std::env::remove_var(LOG_LEVEL_ENV_VAR);
100        }
101    }
102}