Skip to main content

objectstore_log/
subscriber.rs

1use tracing_subscriber::prelude::*;
2use tracing_subscriber::{EnvFilter, Registry};
3
4use crate::config::{LogFormat, LoggingConfig};
5
6// Generated by build.rs: `const CRATE_NAMES: &[&str]` listing all objectstore workspace crates.
7include!(concat!(env!("OUT_DIR"), "/constants.gen.rs"));
8
9/// Initializes the global tracing subscriber with structured logging.
10///
11/// Reads `RUST_LOG` for filter directives; falls back to `INFO`-level logging with `TRACE`-level
12/// for internal objectstore crates. Log format (`pretty`, `simplified`, or `json`) is determined
13/// by `config.format`, defaulting to pretty when a terminal is attached.
14///
15/// When built with the `sentry` feature, also attaches Sentry tracing layers if the Sentry client
16/// has been initialized:
17///
18/// - `ERROR`..`DEBUG` spans become Sentry spans.
19/// - `TRACE` spans are ignored.
20/// - `ERROR`..`DEBUG` events become Sentry logs.
21/// - `ERROR` and `WARN` events also become Sentry error events.
22/// - `TRACE` events are ignored.
23/// - Logs and error events include the attributes of their parent spans.
24pub fn init(config: &LoggingConfig) {
25    #[cfg(feature = "sentry")]
26    let sentry_layer = sentry::Hub::current()
27        .client()
28        .filter(|c| c.is_enabled())
29        .map(|_| sentry_layers());
30
31    let format = tracing_subscriber::fmt::layer()
32        .with_writer(std::io::stderr)
33        .with_target(true);
34
35    let format: Box<dyn tracing_subscriber::Layer<Registry> + Send + Sync> =
36        match (config.format, console::user_attended()) {
37            (LogFormat::Auto, true) | (LogFormat::Pretty, _) => {
38                format.compact().without_time().boxed()
39            }
40            (LogFormat::Auto, false) | (LogFormat::Simplified, _) => {
41                format.with_ansi(false).boxed()
42            }
43            (LogFormat::Json, _) => format
44                .json()
45                .flatten_event(true)
46                .with_current_span(true)
47                .with_span_list(true)
48                .with_file(true)
49                .with_line_number(true)
50                .boxed(),
51        };
52
53    let env_filter = match EnvFilter::try_from_default_env() {
54        Ok(filter) => filter,
55        Err(_) => default_filter(),
56    };
57
58    #[cfg(not(feature = "sentry"))]
59    tracing_subscriber::registry()
60        .with(format.with_filter(config.level))
61        .with(env_filter)
62        .init();
63
64    #[cfg(feature = "sentry")]
65    tracing_subscriber::registry()
66        .with(format.with_filter(config.level))
67        .with(sentry_layer)
68        .with(env_filter)
69        .init();
70}
71
72/// Builds the Sentry tracing layers that [`init`] attaches, with the filtering described there.
73#[cfg(feature = "sentry")]
74fn sentry_layers<S>() -> impl tracing_subscriber::Layer<S>
75where
76    S: tracing::Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a> + 'static,
77{
78    use sentry::integrations::tracing::{ErrorLayer, LogLayer, SpanLayer};
79    use tracing_subscriber::filter::{FilterExt, LevelFilter, filter_fn};
80
81    // Span attributes come only from spans that pass both the SpanLayer's and the ErrorLayer's
82    // filter, so the ErrorLayer accepts all spans. The LogLayer's filter already admits the
83    // same spans as the SpanLayer's.
84    let error_filter = LevelFilter::WARN.or(filter_fn(|metadata| metadata.is_span()));
85
86    SpanLayer::new()
87        .with_filter(LevelFilter::DEBUG)
88        .and_then(
89            ErrorLayer::new()
90                .enable_span_attributes()
91                .with_filter(error_filter),
92        )
93        .and_then(
94            LogLayer::new()
95                .enable_span_attributes()
96                .with_filter(LevelFilter::DEBUG),
97        )
98}
99
100/// Builds the default [`EnvFilter`] when `RUST_LOG` is not set.
101///
102/// Uses `INFO` as the base level. Selected dependencies are raised to `DEBUG` where their debug
103/// logs are low-volume and useful for diagnosing production issues. Every internal objectstore
104/// crate discovered at build time is set to `TRACE`.
105fn default_filter() -> EnvFilter {
106    // Target `bigtable_rs::bigtable` rather than the whole crate: other modules log per request.
107    let mut filter = EnvFilter::new("INFO,tower_http=DEBUG,bigtable_rs::bigtable=DEBUG");
108
109    for name in CRATE_NAMES {
110        // INVARIANT: crate names are valid identifiers; the directive cannot fail to parse.
111        filter = filter.add_directive(format!("{name}=TRACE").parse().unwrap());
112    }
113
114    filter
115}