Skip to main content

reth_tracing/
lib.rs

1//!  The `tracing` module provides functionalities for setting up and configuring logging.
2//!
3//!  It includes structures and functions to create and manage various logging layers: stdout,
4//!  file, or journald. The module's primary entry point is the `Tracer` struct, which can be
5//!  configured to use different logging formats and destinations. If no layer is specified, it will
6//!  default to stdout.
7//!
8//!  # Examples
9//!
10//!  Basic usage:
11//!
12//!  ```
13//!  use reth_tracing::{
14//!      LayerInfo, RethTracer, Tracer,
15//!      tracing::level_filters::LevelFilter,
16//!      LogFormat,
17//!  };
18//!
19//!  fn main() -> eyre::Result<()> {
20//!      let tracer = RethTracer::new().with_stdout(LayerInfo::new(
21//!          LogFormat::Json,
22//!          LevelFilter::INFO.to_string(),
23//!          "debug".to_string(),
24//!          None,
25//!      ));
26//!
27//!      tracer.init()?;
28//!
29//!      // Your application logic here
30//!
31//!      Ok(())
32//!  }
33//!  ```
34//!
35//! This example sets up a tracer with JSON format logging to stdout.
36
37#![doc(
38    html_logo_url = "https://raw.githubusercontent.com/paradigmxyz/reth/main/assets/reth-docs.png",
39    html_favicon_url = "https://avatars0.githubusercontent.com/u/97369466?s=256",
40    issue_tracker_base_url = "https://github.com/paradigmxyz/reth/issues/"
41)]
42#![cfg_attr(not(feature = "std"), no_std)]
43#![cfg_attr(not(test), warn(unused_crate_dependencies))]
44#![cfg_attr(docsrs, feature(doc_cfg))]
45
46// Re-export tracing crates
47pub use tracing;
48#[cfg(feature = "std")]
49pub use tracing_appender;
50#[cfg(feature = "std")]
51pub use tracing_subscriber;
52
53#[cfg(all(feature = "tracy", feature = "std"))]
54tracy_client::register_demangler!();
55
56// Re-export our types
57#[cfg(feature = "std")]
58pub use formatter::LogFormat;
59#[cfg(feature = "std")]
60pub use layers::{FileInfo, FileWorkerGuard, Layers, TracingGuards};
61#[cfg(feature = "std")]
62pub use log_handle::{
63    install_log_handle, log_handle_available, set_log_verbosity, set_log_vmodule,
64    LogFilterReloadHandle,
65};
66#[cfg(feature = "std")]
67pub use test_tracer::TestTracer;
68
69#[cfg(feature = "std")]
70#[doc(hidden)]
71pub mod __private {
72    pub use super::throttle::*;
73}
74
75#[cfg(feature = "std")]
76mod formatter;
77#[cfg(feature = "std")]
78mod layers;
79#[cfg(feature = "std")]
80pub mod log_handle;
81#[cfg(feature = "std")]
82mod rolling;
83#[cfg(feature = "std")]
84mod test_tracer;
85#[cfg(feature = "std")]
86mod throttle;
87
88#[cfg(feature = "std")]
89use tracing::level_filters::LevelFilter;
90#[cfg(feature = "std")]
91use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
92
93///  Tracer for application logging.
94///
95///  Manages the configuration and initialization of logging layers,
96/// including standard output, optional journald, and optional file logging.
97#[cfg(feature = "std")]
98#[derive(Debug, Clone)]
99pub struct RethTracer {
100    stdout: LayerInfo,
101    journald: Option<String>,
102    file: Option<(LayerInfo, FileInfo)>,
103    samply: Option<LayerInfo>,
104    chrome: Option<(LayerInfo, std::path::PathBuf)>,
105    #[cfg(feature = "tracy")]
106    tracy: Option<LayerInfo>,
107    /// When true, the stdout filter is wrapped in a reload layer so log levels
108    /// can be changed at runtime.
109    enable_reload: bool,
110}
111
112#[cfg(feature = "std")]
113impl RethTracer {
114    /// Constructs a new `Tracer` with default settings.
115    ///
116    /// Initializes with default stdout layer configuration.
117    /// Journald and file layers are not set by default.
118    pub fn new() -> Self {
119        Self {
120            stdout: LayerInfo::default(),
121            journald: None,
122            file: None,
123            samply: None,
124            chrome: None,
125            #[cfg(feature = "tracy")]
126            tracy: None,
127            enable_reload: false,
128        }
129    }
130
131    /// Sets a custom configuration for the stdout layer.
132    ///
133    /// # Arguments
134    /// * `config` - The `LayerInfo` to use for the stdout layer.
135    pub fn with_stdout(mut self, config: LayerInfo) -> Self {
136        self.stdout = config;
137        self
138    }
139
140    /// Sets the journald layer filter.
141    ///
142    /// # Arguments
143    /// * `filter` - The `filter` to use for the journald layer.
144    pub fn with_journald(mut self, filter: String) -> Self {
145        self.journald = Some(filter);
146        self
147    }
148
149    /// Sets the file layer configuration and associated file info.
150    ///
151    ///  # Arguments
152    /// * `config` - The `LayerInfo` to use for the file layer.
153    /// * `file_info` - The `FileInfo` containing details about the log file.
154    pub fn with_file(mut self, config: LayerInfo, file_info: FileInfo) -> Self {
155        self.file = Some((config, file_info));
156        self
157    }
158
159    /// Sets the samply layer configuration.
160    pub fn with_samply(mut self, config: LayerInfo) -> Self {
161        self.samply = Some(config);
162        self
163    }
164
165    /// Sets the Chrome trace layer configuration.
166    pub fn with_chrome(mut self, config: LayerInfo, file: std::path::PathBuf) -> Self {
167        self.chrome = Some((config, file));
168        self
169    }
170
171    /// Sets the tracy layer configuration.
172    #[cfg(feature = "tracy")]
173    pub fn with_tracy(mut self, config: LayerInfo) -> Self {
174        self.tracy = Some(config);
175        self
176    }
177
178    /// Enables runtime log filter reloading.
179    pub const fn with_reload(mut self, enable: bool) -> Self {
180        self.enable_reload = enable;
181        self
182    }
183}
184
185#[cfg(feature = "std")]
186impl Default for RethTracer {
187    fn default() -> Self {
188        Self::new()
189    }
190}
191
192///  Configuration for a logging layer.
193///
194///  This struct holds configuration parameters for a tracing layer, including
195///  the format, filtering directives, optional coloring, and directive.
196#[cfg(feature = "std")]
197#[derive(Debug, Clone)]
198pub struct LayerInfo {
199    format: LogFormat,
200    default_directive: String,
201    filters: String,
202    color: Option<String>,
203}
204
205#[cfg(feature = "std")]
206impl LayerInfo {
207    ///  Constructs a new `LayerInfo`.
208    ///
209    ///  # Arguments
210    ///  * `format` - Specifies the format for log messages. Possible values are:
211    ///      - `LogFormat::Json` for JSON formatting.
212    ///      - `LogFormat::LogFmt` for logfmt (key=value) formatting.
213    ///      - `LogFormat::Terminal` for human-readable, terminal-friendly formatting.
214    ///  * `default_directive` - Directive for filtering log messages.
215    ///  * `filters` - Additional filtering parameters as a string.
216    ///  * `color` - Optional color configuration for the log messages.
217    pub const fn new(
218        format: LogFormat,
219        default_directive: String,
220        filters: String,
221        color: Option<String>,
222    ) -> Self {
223        Self { format, default_directive, filters, color }
224    }
225}
226
227#[cfg(feature = "std")]
228impl Default for LayerInfo {
229    ///  Provides default values for `LayerInfo`.
230    ///
231    ///  By default, it uses terminal format, INFO level filter,
232    ///  no additional filters, and no color configuration.
233    fn default() -> Self {
234        Self {
235            format: LogFormat::Terminal,
236            default_directive: LevelFilter::INFO.to_string(),
237            filters: String::new(),
238            color: Some("always".to_string()),
239        }
240    }
241}
242
243/// Trait defining a general interface for logging configuration.
244///
245/// The `Tracer` trait provides a standardized way to initialize logging configurations
246/// in an application. Implementations of this trait can specify different logging setups,
247/// such as standard output logging, file logging, journald logging, or custom logging
248/// configurations tailored for specific environments (like testing).
249#[cfg(feature = "std")]
250pub trait Tracer: Sized {
251    /// Initialize the logging configuration.
252    ///
253    /// By default, this method creates a new `Layers` instance and delegates to `init_with_layers`.
254    ///
255    /// # Returns
256    /// An `eyre::Result` with guards for layers that need to stay alive, or an `Err` in case of an
257    /// error during initialization.
258    fn init(self) -> eyre::Result<TracingGuards> {
259        self.init_with_layers(Layers::new())
260    }
261
262    /// Initialize the logging configuration with additional custom layers.
263    ///
264    /// This is the primary method that implementors must provide.
265    ///
266    /// # Arguments
267    /// * `layers` - Pre-configured `Layers` instance to use for initialization
268    ///
269    /// # Returns
270    /// An `eyre::Result` with guards for layers that need to stay alive, or an `Err` in case of an
271    /// error during initialization.
272    fn init_with_layers(self, layers: Layers) -> eyre::Result<TracingGuards>;
273}
274
275#[cfg(feature = "std")]
276impl Tracer for RethTracer {
277    fn init_with_layers(self, mut layers: Layers) -> eyre::Result<TracingGuards> {
278        // Configure stdout layer - reloadable if requested for runtime log level changes
279        if let Some(handle) = layers.stdout(
280            self.stdout.format,
281            self.stdout.default_directive.parse()?,
282            &self.stdout.filters,
283            self.stdout.color,
284            self.enable_reload,
285        )? {
286            install_log_handle(handle);
287        }
288
289        if let Some(config) = self.journald {
290            layers.journald(&config)?;
291        }
292
293        let file_guard = if let Some((config, file_info)) = self.file {
294            let (guard, handle) =
295                layers.file(config.format, &config.filters, file_info, self.enable_reload)?;
296            if let Some(handle) = handle {
297                install_log_handle(handle);
298            }
299            Some(guard)
300        } else {
301            None
302        };
303
304        if let Some(config) = self.samply {
305            layers.samply(config)?;
306        }
307
308        let chrome_guard = if let Some((config, file)) = self.chrome {
309            Some(layers.chrome(config, &file)?)
310        } else {
311            None
312        };
313
314        #[cfg(feature = "tracy")]
315        if let Some(config) = self.tracy {
316            layers.tracy(config)?;
317        }
318
319        // The error is returned if the global default subscriber is already set,
320        // so it's safe to ignore it
321        let _ = tracing_subscriber::registry().with(layers.into_inner()).try_init();
322
323        Ok(TracingGuards::new(file_guard, chrome_guard))
324    }
325}
326
327///  Initializes a tracing subscriber for tests.
328///
329///  The filter is configurable via `RUST_LOG`.
330///
331///  # Note
332///
333///  The subscriber will silently fail if it could not be installed.
334#[cfg(feature = "std")]
335pub fn init_test_tracing() {
336    let _ = TestTracer::default().init();
337}