molten_api/telemetry.rs
1//! This module provides utilities for setting up application-wide logging and tracing.
2//!
3//! It leverages the `tracing` and `tracing-subscriber` crates to configure
4//! how log events and spans are collected and emitted, allowing for better
5//! observability of the Molten API.
6use tracing::Subscriber;
7use tracing::subscriber::set_global_default;
8use tracing_log::LogTracer;
9use tracing_subscriber::fmt::MakeWriter;
10use tracing_subscriber::{EnvFilter, Registry, layer::SubscriberExt};
11
12/// Returns a `Subscriber` that can be used for logging and tracing.
13///
14/// This function configures an `EnvFilter` to filter log events based on
15/// environment variables or a default filter string, and sets up a `fmt` layer
16/// for formatting and outputting log records to a specified sink.
17///
18/// # Arguments
19/// * `env_filter` - A string defining the default logging level and filter directives.
20/// * `sink` - A type that implements `MakeWriter` trait, determining where the logs are written (e.g., `stdout`, `stderr`, a file).
21///
22/// # Type Parameters
23/// * `Sink` - A type that can create `std::io::Write` instances, enabling flexible log output.
24///
25/// # Returns
26/// An `impl Subscriber + Send + Sync` configured with the specified filter and sink.
27pub fn get_subscriber<Sink>(env_filter: String, sink: Sink) -> impl Subscriber + Send + Sync
28where
29 // Function is generic for MakeWriter trait allowing us to choose
30 // where messages are written to (e.g., std::io::{stdout, sink} )
31 Sink: for<'a> MakeWriter<'a> + Send + Sync + 'static,
32{
33 let env_filter = EnvFilter::try_from_default_env()
34 // If no RUST_LOG env variable is set, set the Env Filter manually
35 .or_else(|_| EnvFilter::try_new(env_filter))
36 .expect("Unable to set logging level.");
37 let formatting_layer = tracing_subscriber::fmt::layer().with_writer(sink);
38
39 Registry::default().with(env_filter).with(formatting_layer)
40}
41
42/// Initializes the global default tracing subscriber.
43///
44/// This function sets the provided `subscriber` as the global default for processing
45/// `tracing` spans and events. It also redirects `log` crate events to this subscriber.
46///
47/// # Arguments
48/// * `subscriber` - An `impl Subscriber + Send + Sync` which will be set as the global default.
49///
50/// # Panics
51/// Panics if unable to set the global logger or subscriber, typically indicating
52/// that a subscriber has already been set.
53pub fn init_subscriber(subscriber: impl Subscriber + Send + Sync) {
54 // Redirect `log`'s events to the subscriber
55 LogTracer::init().expect("Failed to set logger");
56 // set_global_default specifies the subscriber used to process spans
57 set_global_default(subscriber).expect("Failed to set subscriber");
58}