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 for journald and terminal-friendly
36//! format for file logging.
37
38#![doc(
39 html_logo_url = "https://raw.githubusercontent.com/paradigmxyz/reth/main/assets/reth-docs.png",
40 html_favicon_url = "https://avatars0.githubusercontent.com/u/97369466?s=256",
41 issue_tracker_base_url = "https://github.com/paradigmxyz/reth/issues/"
42)]
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;
48pub use tracing_appender;
49pub use tracing_subscriber;
50
51// Re-export our types
52pub use formatter::LogFormat;
53pub use layers::{FileInfo, FileWorkerGuard, Layers};
54pub use test_tracer::TestTracer;
55
56mod formatter;
57mod layers;
58mod test_tracer;
59
60use tracing::level_filters::LevelFilter;
61use tracing_appender::non_blocking::WorkerGuard;
62use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
63
64/// Tracer for application logging.
65///
66/// Manages the configuration and initialization of logging layers,
67/// including standard output, optional journald, and optional file logging.
68#[derive(Debug, Clone)]
69pub struct RethTracer {
70 stdout: LayerInfo,
71 journald: Option<String>,
72 file: Option<(LayerInfo, FileInfo)>,
73 samply: Option<LayerInfo>,
74}
75
76impl RethTracer {
77 /// Constructs a new `Tracer` with default settings.
78 ///
79 /// Initializes with default stdout layer configuration.
80 /// Journald and file layers are not set by default.
81 pub fn new() -> Self {
82 Self { stdout: LayerInfo::default(), journald: None, file: None, samply: None }
83 }
84
85 /// Sets a custom configuration for the stdout layer.
86 ///
87 /// # Arguments
88 /// * `config` - The `LayerInfo` to use for the stdout layer.
89 pub fn with_stdout(mut self, config: LayerInfo) -> Self {
90 self.stdout = config;
91 self
92 }
93
94 /// Sets the journald layer filter.
95 ///
96 /// # Arguments
97 /// * `filter` - The `filter` to use for the journald layer.
98 pub fn with_journald(mut self, filter: String) -> Self {
99 self.journald = Some(filter);
100 self
101 }
102
103 /// Sets the file layer configuration and associated file info.
104 ///
105 /// # Arguments
106 /// * `config` - The `LayerInfo` to use for the file layer.
107 /// * `file_info` - The `FileInfo` containing details about the log file.
108 pub fn with_file(mut self, config: LayerInfo, file_info: FileInfo) -> Self {
109 self.file = Some((config, file_info));
110 self
111 }
112
113 /// Sets the samply layer configuration.
114 pub fn with_samply(mut self, config: LayerInfo) -> Self {
115 self.samply = Some(config);
116 self
117 }
118}
119
120impl Default for RethTracer {
121 fn default() -> Self {
122 Self::new()
123 }
124}
125
126/// Configuration for a logging layer.
127///
128/// This struct holds configuration parameters for a tracing layer, including
129/// the format, filtering directives, optional coloring, and directive.
130#[derive(Debug, Clone)]
131pub struct LayerInfo {
132 format: LogFormat,
133 default_directive: String,
134 filters: String,
135 color: Option<String>,
136}
137
138impl LayerInfo {
139 /// Constructs a new `LayerInfo`.
140 ///
141 /// # Arguments
142 /// * `format` - Specifies the format for log messages. Possible values are:
143 /// - `LogFormat::Json` for JSON formatting.
144 /// - `LogFormat::LogFmt` for logfmt (key=value) formatting.
145 /// - `LogFormat::Terminal` for human-readable, terminal-friendly formatting.
146 /// * `default_directive` - Directive for filtering log messages.
147 /// * `filters` - Additional filtering parameters as a string.
148 /// * `color` - Optional color configuration for the log messages.
149 pub const fn new(
150 format: LogFormat,
151 default_directive: String,
152 filters: String,
153 color: Option<String>,
154 ) -> Self {
155 Self { format, default_directive, filters, color }
156 }
157}
158
159impl Default for LayerInfo {
160 /// Provides default values for `LayerInfo`.
161 ///
162 /// By default, it uses terminal format, INFO level filter,
163 /// no additional filters, and no color configuration.
164 fn default() -> Self {
165 Self {
166 format: LogFormat::Terminal,
167 default_directive: LevelFilter::INFO.to_string(),
168 filters: String::new(),
169 color: Some("always".to_string()),
170 }
171 }
172}
173
174/// Trait defining a general interface for logging configuration.
175///
176/// The `Tracer` trait provides a standardized way to initialize logging configurations
177/// in an application. Implementations of this trait can specify different logging setups,
178/// such as standard output logging, file logging, journald logging, or custom logging
179/// configurations tailored for specific environments (like testing).
180pub trait Tracer: Sized {
181 /// Initialize the logging configuration.
182 ///
183 /// By default, this method creates a new `Layers` instance and delegates to `init_with_layers`.
184 ///
185 /// # Returns
186 /// An `eyre::Result` which is `Ok` with an optional `WorkerGuard` if a file layer is used,
187 /// or an `Err` in case of an error during initialization.
188 fn init(self) -> eyre::Result<Option<WorkerGuard>> {
189 self.init_with_layers(Layers::new())
190 }
191 /// Initialize the logging configuration with additional custom layers.
192 ///
193 /// This method allows for more customized setup by accepting pre-configured
194 /// `Layers` which can be further customized before initialization.
195 ///
196 /// # Arguments
197 /// * `layers` - Pre-configured `Layers` instance to use for initialization
198 ///
199 /// # Returns
200 /// An `eyre::Result` which is `Ok` with an optional `WorkerGuard` if a file layer is used,
201 /// or an `Err` in case of an error during initialization.
202 fn init_with_layers(self, layers: Layers) -> eyre::Result<Option<WorkerGuard>>;
203}
204
205impl Tracer for RethTracer {
206 /// Initializes the logging system based on the configured layers.
207 ///
208 /// This method sets up the global tracing subscriber with the specified
209 /// stdout, journald, and file layers.
210 ///
211 /// The default layer is stdout.
212 ///
213 /// # Returns
214 /// An `eyre::Result` which is `Ok` with an optional `WorkerGuard` if a file layer is used,
215 /// or an `Err` in case of an error during initialization.
216 fn init_with_layers(self, mut layers: Layers) -> eyre::Result<Option<WorkerGuard>> {
217 layers.stdout(
218 self.stdout.format,
219 self.stdout.default_directive.parse()?,
220 &self.stdout.filters,
221 self.stdout.color,
222 )?;
223
224 if let Some(config) = self.journald {
225 layers.journald(&config)?;
226 }
227
228 let file_guard = if let Some((config, file_info)) = self.file {
229 Some(layers.file(config.format, &config.filters, file_info)?)
230 } else {
231 None
232 };
233
234 if let Some(config) = self.samply {
235 layers.samply(config)?;
236 }
237
238 // The error is returned if the global default subscriber is already set,
239 // so it's safe to ignore it
240 let _ = tracing_subscriber::registry().with(layers.into_inner()).try_init();
241 Ok(file_guard)
242 }
243}
244
245/// Initializes a tracing subscriber for tests.
246///
247/// The filter is configurable via `RUST_LOG`.
248///
249/// # Note
250///
251/// The subscriber will silently fail if it could not be installed.
252pub fn init_test_tracing() {
253 let _ = TestTracer::default().init();
254}