Skip to main content

zebrad/components/
tracing.rs

1//! Tracing and logging infrastructure for Zebra.
2
3use std::{
4    io::IsTerminal,
5    net::SocketAddr,
6    ops::{Deref, DerefMut},
7    path::PathBuf,
8};
9
10use serde::{Deserialize, Serialize};
11
12mod component;
13mod endpoint;
14mod format;
15
16#[cfg(feature = "flamegraph")]
17mod flame;
18
19#[cfg(feature = "opentelemetry")]
20mod otel;
21
22pub use component::Tracing;
23pub use endpoint::TracingEndpoint;
24pub(crate) use format::json_panic_line;
25
26#[cfg(feature = "flamegraph")]
27pub use flame::{layer, Grapher};
28
29/// Tracing configuration section: outer config after cross-field defaults are applied.
30///
31/// This is a wrapper type that dereferences to the inner config type.
32///
33//
34// TODO: replace with serde's finalizer attribute when that feature is implemented.
35//       we currently use the recommended workaround of a wrapper struct with from/into attributes.
36//       https://github.com/serde-rs/serde/issues/642#issuecomment-525432907
37#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
38#[serde(
39    deny_unknown_fields,
40    default,
41    from = "InnerConfig",
42    into = "InnerConfig"
43)]
44pub struct Config {
45    inner: InnerConfig,
46}
47
48impl Deref for Config {
49    type Target = InnerConfig;
50
51    fn deref(&self) -> &Self::Target {
52        &self.inner
53    }
54}
55
56impl DerefMut for Config {
57    fn deref_mut(&mut self) -> &mut Self::Target {
58        &mut self.inner
59    }
60}
61
62impl From<InnerConfig> for Config {
63    fn from(mut inner: InnerConfig) -> Self {
64        inner.log_file = runtime_default_log_file(inner.log_file, inner.progress_bar);
65
66        Self { inner }
67    }
68}
69
70impl From<Config> for InnerConfig {
71    fn from(mut config: Config) -> Self {
72        config.log_file = disk_default_log_file(config.log_file.clone(), config.progress_bar);
73
74        config.inner
75    }
76}
77
78/// Tracing configuration section: inner config used to deserialize and apply cross-field defaults.
79#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
80#[serde(deny_unknown_fields, default)]
81pub struct InnerConfig {
82    /// Whether to use colored terminal output, if available.
83    ///
84    /// Colored terminal output is automatically disabled if an output stream
85    /// is connected to a file. (Or another non-terminal device.)
86    ///
87    /// Defaults to `true`, which automatically enables colored output to
88    /// terminals.
89    pub use_color: bool,
90
91    /// Whether to force the use of colored terminal output, even if it's not available.
92    ///
93    /// Will force Zebra to use colored terminal output even if it does not detect that the output
94    /// is a terminal that supports colors.
95    ///
96    /// Defaults to `false`, which keeps the behavior of `use_color`.
97    pub force_use_color: bool,
98
99    /// The filter used for tracing events.
100    ///
101    /// The filter is used to create a `tracing-subscriber`
102    /// [`EnvFilter`](https://docs.rs/tracing-subscriber/0.2.10/tracing_subscriber/filter/struct.EnvFilter.html#directives),
103    /// and more details on the syntax can be found there or in the examples
104    /// below.
105    ///
106    /// If no filter is specified (`None`), the filter is set to `info` if the
107    /// `-v` flag is given and `warn` if it is not given.
108    ///
109    /// # Examples
110    ///
111    /// `warn,zebrad=info,zebra_network=debug` sets a global `warn` level, an
112    /// `info` level for the `zebrad` crate, and a `debug` level for the
113    /// `zebra_network` crate.
114    ///
115    /// ```ascii,no_run
116    /// [block_verify{height=Some\(block::Height\(.*000\)\)}]=trace
117    /// ```
118    /// sets `trace` level for all events occurring in the context of a
119    /// `block_verify` span whose `height` field ends in `000`, i.e., traces the
120    /// verification of every 1000th block.
121    pub filter: Option<String>,
122
123    /// The buffer_limit size sets the number of log lines that can be queued by the tracing subscriber
124    /// to be written to stdout before logs are dropped.
125    ///
126    /// Defaults to 128,000 with a minimum of 100.
127    pub buffer_limit: usize,
128
129    /// The address used for an ad-hoc RPC endpoint allowing dynamic control of the tracing filter.
130    ///
131    /// Install Zebra using `cargo install --features=filter-reload` to enable this config.
132    ///
133    /// If this is set to None, the endpoint is disabled.
134    pub endpoint_addr: Option<SocketAddr>,
135
136    /// Controls whether to write a flamegraph of tracing spans.
137    ///
138    /// Install Zebra using `cargo install --features=flamegraph` to enable this config.
139    ///
140    /// If this is set to None, flamegraphs are disabled. Otherwise, it specifies
141    /// an output file path, as described below.
142    ///
143    /// This path is not used verbatim when writing out the flamegraph. This is
144    /// because the flamegraph is written out as two parts. First the flamegraph
145    /// is constantly persisted to the disk in a "folded" representation that
146    /// records collapsed stack traces of the tracing spans that are active.
147    /// Then, when the application is finished running the destructor will flush
148    /// the flamegraph output to the folded file and then read that file and
149    /// generate the final flamegraph from it as an SVG.
150    ///
151    /// The need to create two files means that we will slightly manipulate the
152    /// path given to us to create the two representations.
153    ///
154    /// # Security
155    ///
156    /// If you are running Zebra with elevated permissions ("root"), create the
157    /// directory for this file before running Zebra, and make sure the Zebra user
158    /// account has exclusive access to that directory, and other users can't modify
159    /// its parent directories.
160    ///
161    /// # Example
162    ///
163    /// Given `flamegraph = "flamegraph"` we will generate a `flamegraph.svg` and
164    /// a `flamegraph.folded` file in the current directory.
165    ///
166    /// If you provide a path with an extension the extension will be ignored and
167    /// replaced with `.folded` and `.svg` for the respective files.
168    pub flamegraph: Option<PathBuf>,
169
170    /// Shows progress bars for block syncing, and mempool transactions, and peer networking.
171    /// Also sends logs to the default log file path.
172    ///
173    /// This config field is ignored unless the `progress-bar` feature is enabled.
174    pub progress_bar: Option<ProgressConfig>,
175
176    /// If set to a path, write the tracing logs to that path.
177    ///
178    /// By default, logs are sent to the terminal standard output.
179    /// But if the `progress_bar` config is activated, logs are sent to the standard log file path:
180    /// - Linux: `$XDG_STATE_HOME/zebrad.log` or `$HOME/.local/state/zebrad.log`
181    /// - macOS: `$HOME/Library/Application Support/zebrad.log`
182    /// - Windows: `%LOCALAPPDATA%\zebrad.log` or `C:\Users\%USERNAME%\AppData\Local\zebrad.log`
183    ///
184    /// # Security
185    ///
186    /// If you are running Zebra with elevated permissions ("root"), create the
187    /// directory for this file before running Zebra, and make sure the Zebra user
188    /// account has exclusive access to that directory, and other users can't modify
189    /// its parent directories.
190    pub log_file: Option<PathBuf>,
191
192    /// The format of the logs written to standard output or the log file.
193    ///
194    /// Defaults to `"text"`. Set to `"json"` to write one JSON object per line, for log
195    /// collectors such as Google Cloud Logging, Azure Monitor, Grafana Loki, and Datadog.
196    /// JSON logs never use color.
197    pub log_format: LogFormat,
198
199    /// The use_journald flag sends tracing events to systemd-journald, on Linux
200    /// distributions that use systemd.
201    ///
202    /// Install Zebra using `cargo install --features=journald` to enable this config.
203    pub use_journald: bool,
204
205    /// OpenTelemetry OTLP endpoint URL for distributed tracing.
206    ///
207    /// Install Zebra using `cargo install --features=opentelemetry` to enable this config.
208    ///
209    /// When `None` (default), OpenTelemetry is completely disabled with zero runtime overhead.
210    /// When set, traces are exported via OTLP HTTP protocol.
211    ///
212    /// Example: `"http://localhost:4318"`
213    ///
214    /// Can also be set via `OTEL_EXPORTER_OTLP_ENDPOINT` environment variable (lower precedence).
215    pub opentelemetry_endpoint: Option<String>,
216
217    /// Service name reported to OpenTelemetry collector.
218    ///
219    /// Defaults to `"zebra"` if not specified.
220    ///
221    /// Can also be set via `OTEL_SERVICE_NAME` environment variable.
222    pub opentelemetry_service_name: Option<String>,
223
224    /// Trace sampling percentage between 0 and 100.
225    ///
226    /// Controls what percentage of traces are exported:
227    /// - `100` = 100% (all traces, default)
228    /// - `10` = 10% (recommended for high-traffic production)
229    /// - `0` = 0% (effectively disabled)
230    ///
231    /// Lower values reduce network/collector overhead for busy nodes.
232    ///
233    /// When `None` (default), the standard `OTEL_TRACES_SAMPLER` and
234    /// `OTEL_TRACES_SAMPLER_ARG` environment variables choose the sampler, and every
235    /// trace is sampled if they are unset. Unlike this setting, `OTEL_TRACES_SAMPLER_ARG`
236    /// is a ratio between 0.0 and 1.0, and only applies when `OTEL_TRACES_SAMPLER` is set.
237    pub opentelemetry_sample_percent: Option<u8>,
238}
239
240/// The format of Zebra's logs.
241#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
242#[serde(rename_all = "lowercase")]
243pub enum LogFormat {
244    /// Human-readable text, one event per line.
245    #[default]
246    Text,
247
248    /// One JSON object per line.
249    ///
250    /// Each line has the keys `timestamp`, `level`, `severity`, `message`, and `target`,
251    /// followed by the event's fields, the `spans` it happened in, its `code.file.path` and
252    /// `code.line.number`, and its OpenTelemetry `trace_id` and `span_id` if it is in a
253    /// sampled trace. Only these keys are stable: event and span fields can change between
254    /// releases.
255    Json,
256}
257
258/// The progress bars that Zebra will show while running.
259#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
260#[serde(rename_all = "lowercase")]
261pub enum ProgressConfig {
262    /// Show a lot of progress bars.
263    Detailed,
264
265    /// Show a few important progress bars.
266    //
267    // TODO: actually hide some progress bars in this mode.
268    #[default]
269    #[serde(other)]
270    Summary,
271}
272
273impl Config {
274    /// Returns `true` if standard output should use color escapes.
275    /// Automatically checks if Zebra is running in a terminal, and never uses color for JSON logs.
276    pub fn use_color_stdout(&self) -> bool {
277        self.log_format == LogFormat::Text
278            && (self.force_use_color || (self.use_color && std::io::stdout().is_terminal()))
279    }
280
281    /// Returns `true` if standard error should use color escapes.
282    /// Automatically checks if Zebra is running in a terminal.
283    pub fn use_color_stderr(&self) -> bool {
284        self.force_use_color || (self.use_color && std::io::stderr().is_terminal())
285    }
286
287    /// Returns `true` if output that could go to standard output or standard error
288    /// should use color escapes. Automatically checks if Zebra is running in a terminal.
289    pub fn use_color_stdout_and_stderr(&self) -> bool {
290        self.force_use_color
291            || (self.use_color
292                && std::io::stdout().is_terminal()
293                && std::io::stderr().is_terminal())
294    }
295}
296
297impl Default for InnerConfig {
298    fn default() -> Self {
299        // TODO: enable progress bars by default once they have been tested
300        let progress_bar = None;
301
302        Self {
303            use_color: true,
304            force_use_color: false,
305            filter: None,
306            buffer_limit: 128_000,
307            endpoint_addr: None,
308            flamegraph: None,
309            progress_bar,
310            log_file: runtime_default_log_file(None, progress_bar),
311            log_format: LogFormat::Text,
312            use_journald: false,
313            opentelemetry_endpoint: None,
314            opentelemetry_service_name: None,
315            opentelemetry_sample_percent: None,
316        }
317    }
318}
319
320/// Returns the runtime default log file path based on the `log_file` and `progress_bar` configs.
321fn runtime_default_log_file(
322    log_file: Option<PathBuf>,
323    progress_bar: Option<ProgressConfig>,
324) -> Option<PathBuf> {
325    if let Some(log_file) = log_file {
326        return Some(log_file);
327    }
328
329    // If the progress bar is active, we want to use a log file regardless of the config.
330    // (Logging to a terminal erases parts of the progress bars, making both unreadable.)
331    if progress_bar.is_some() {
332        return default_log_file();
333    }
334
335    None
336}
337
338/// Returns the configured log file path using the runtime `log_file` and `progress_bar` config.
339///
340/// This is the inverse of [`runtime_default_log_file()`].
341fn disk_default_log_file(
342    log_file: Option<PathBuf>,
343    progress_bar: Option<ProgressConfig>,
344) -> Option<PathBuf> {
345    // If the progress bar is active, and we've likely substituted the default log file path,
346    // don't write that substitute to the config on disk.
347    if progress_bar.is_some() && log_file == default_log_file() {
348        return None;
349    }
350
351    log_file
352}
353
354/// Returns the default log file path.
355fn default_log_file() -> Option<PathBuf> {
356    dirs::state_dir()
357        .or_else(dirs::data_local_dir)
358        .map(|dir| dir.join("zebrad.log"))
359}