reth_node_core/args/
log.rs

1//! clap [Args](clap::Args) for logging configuration.
2
3use crate::dirs::{LogsDir, PlatformPath};
4use clap::{ArgAction, Args, ValueEnum};
5use reth_tracing::{
6    tracing_subscriber::filter::Directive, FileInfo, FileWorkerGuard, LayerInfo, Layers, LogFormat,
7    RethTracer, Tracer,
8};
9use std::{fmt, fmt::Display};
10use tracing::{level_filters::LevelFilter, Level};
11/// Constant to convert megabytes to bytes
12const MB_TO_BYTES: u64 = 1024 * 1024;
13
14/// The log configuration.
15#[derive(Debug, Args)]
16#[command(next_help_heading = "Logging")]
17pub struct LogArgs {
18    /// The format to use for logs written to stdout.
19    #[arg(long = "log.stdout.format", value_name = "FORMAT", global = true, default_value_t = LogFormat::Terminal)]
20    pub log_stdout_format: LogFormat,
21
22    /// The filter to use for logs written to stdout.
23    #[arg(long = "log.stdout.filter", value_name = "FILTER", global = true, default_value = "")]
24    pub log_stdout_filter: String,
25
26    /// The format to use for logs written to the log file.
27    #[arg(long = "log.file.format", value_name = "FORMAT", global = true, default_value_t = LogFormat::Terminal)]
28    pub log_file_format: LogFormat,
29
30    /// The filter to use for logs written to the log file.
31    #[arg(long = "log.file.filter", value_name = "FILTER", global = true, default_value = "debug")]
32    pub log_file_filter: String,
33
34    /// The path to put log files in.
35    #[arg(long = "log.file.directory", value_name = "PATH", global = true, default_value_t)]
36    pub log_file_directory: PlatformPath<LogsDir>,
37
38    /// The prefix name of the log files.
39    #[arg(long = "log.file.name", value_name = "NAME", global = true, default_value = "reth.log")]
40    pub log_file_name: String,
41
42    /// The maximum size (in MB) of one log file.
43    #[arg(long = "log.file.max-size", value_name = "SIZE", global = true, default_value_t = 200)]
44    pub log_file_max_size: u64,
45
46    /// The maximum amount of log files that will be stored. If set to 0, background file logging
47    /// is disabled.
48    #[arg(long = "log.file.max-files", value_name = "COUNT", global = true, default_value_t = 5)]
49    pub log_file_max_files: usize,
50
51    /// Write logs to journald.
52    #[arg(long = "log.journald", global = true)]
53    pub journald: bool,
54
55    /// The filter to use for logs written to journald.
56    #[arg(
57        long = "log.journald.filter",
58        value_name = "FILTER",
59        global = true,
60        default_value = "error"
61    )]
62    pub journald_filter: String,
63
64    /// Emit traces to samply. Only useful when profiling.
65    #[arg(long = "log.samply", global = true, hide = true)]
66    pub samply: bool,
67
68    /// The filter to use for traces emitted to samply.
69    #[arg(
70        long = "log.samply.filter",
71        value_name = "FILTER",
72        global = true,
73        default_value = "debug",
74        hide = true
75    )]
76    pub samply_filter: String,
77
78    /// Sets whether or not the formatter emits ANSI terminal escape codes for colors and other
79    /// text formatting.
80    #[arg(
81        long,
82        value_name = "COLOR",
83        global = true,
84        default_value_t = ColorMode::Always
85    )]
86    pub color: ColorMode,
87
88    /// The verbosity settings for the tracer.
89    #[command(flatten)]
90    pub verbosity: Verbosity,
91}
92
93impl LogArgs {
94    /// Creates a [`LayerInfo`] instance.
95    fn layer_info(&self, format: LogFormat, filter: String, use_color: bool) -> LayerInfo {
96        LayerInfo::new(
97            format,
98            self.verbosity.directive().to_string(),
99            filter,
100            use_color.then(|| self.color.to_string()),
101        )
102    }
103
104    /// File info from the current log options.
105    fn file_info(&self) -> FileInfo {
106        FileInfo::new(
107            self.log_file_directory.clone().into(),
108            self.log_file_name.clone(),
109            self.log_file_max_size * MB_TO_BYTES,
110            self.log_file_max_files,
111        )
112    }
113
114    /// Initializes tracing with the configured options from cli args.
115    ///
116    /// Uses default layers for tracing. If you need to include custom layers,
117    /// use `init_tracing_with_layers` instead.
118    ///
119    /// Returns the file worker guard if a file worker was configured.
120    pub fn init_tracing(&self) -> eyre::Result<Option<FileWorkerGuard>> {
121        self.init_tracing_with_layers(Layers::new())
122    }
123
124    /// Initializes tracing with the configured options from cli args.
125    ///
126    /// Returns the file worker guard, and the file name, if a file worker was configured.
127    pub fn init_tracing_with_layers(
128        &self,
129        layers: Layers,
130    ) -> eyre::Result<Option<FileWorkerGuard>> {
131        let mut tracer = RethTracer::new();
132
133        let stdout = self.layer_info(self.log_stdout_format, self.log_stdout_filter.clone(), true);
134        tracer = tracer.with_stdout(stdout);
135
136        if self.journald {
137            tracer = tracer.with_journald(self.journald_filter.clone());
138        }
139
140        if self.log_file_max_files > 0 {
141            let info = self.file_info();
142            let file = self.layer_info(self.log_file_format, self.log_file_filter.clone(), false);
143            tracer = tracer.with_file(file, info);
144        }
145
146        if self.samply {
147            let config = self.layer_info(LogFormat::Terminal, self.samply_filter.clone(), false);
148            tracer = tracer.with_samply(config);
149        }
150
151        let guard = tracer.init_with_layers(layers)?;
152        Ok(guard)
153    }
154}
155
156/// The color mode for the cli.
157#[derive(Debug, Copy, Clone, ValueEnum, Eq, PartialEq)]
158pub enum ColorMode {
159    /// Colors on
160    Always,
161    /// Auto-detect
162    Auto,
163    /// Colors off
164    Never,
165}
166
167impl Display for ColorMode {
168    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
169        match self {
170            Self::Always => write!(f, "always"),
171            Self::Auto => write!(f, "auto"),
172            Self::Never => write!(f, "never"),
173        }
174    }
175}
176
177/// The verbosity settings for the cli.
178#[derive(Debug, Copy, Clone, Args)]
179#[command(next_help_heading = "Display")]
180pub struct Verbosity {
181    /// Set the minimum log level.
182    ///
183    /// -v      Errors
184    /// -vv     Warnings
185    /// -vvv    Info
186    /// -vvvv   Debug
187    /// -vvvvv  Traces (warning: very verbose!)
188    #[arg(short, long, action = ArgAction::Count, global = true, default_value_t = 3, verbatim_doc_comment, help_heading = "Display")]
189    verbosity: u8,
190
191    /// Silence all log output.
192    #[arg(long, alias = "silent", short = 'q', global = true, help_heading = "Display")]
193    quiet: bool,
194}
195
196impl Verbosity {
197    /// Get the corresponding [Directive] for the given verbosity, or none if the verbosity
198    /// corresponds to silent.
199    pub fn directive(&self) -> Directive {
200        if self.quiet {
201            LevelFilter::OFF.into()
202        } else {
203            let level = match self.verbosity - 1 {
204                0 => Level::ERROR,
205                1 => Level::WARN,
206                2 => Level::INFO,
207                3 => Level::DEBUG,
208                _ => Level::TRACE,
209            };
210
211            level.into()
212        }
213    }
214}