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    /// Sets whether or not the formatter emits ANSI terminal escape codes for colors and other
65    /// text formatting.
66    #[arg(
67        long,
68        value_name = "COLOR",
69        global = true,
70        default_value_t = ColorMode::Always
71    )]
72    pub color: ColorMode,
73    /// The verbosity settings for the tracer.
74    #[command(flatten)]
75    pub verbosity: Verbosity,
76}
77
78impl LogArgs {
79    /// Creates a [`LayerInfo`] instance.
80    fn layer_info(&self, format: LogFormat, filter: String, use_color: bool) -> LayerInfo {
81        LayerInfo::new(
82            format,
83            self.verbosity.directive().to_string(),
84            filter,
85            use_color.then(|| self.color.to_string()),
86        )
87    }
88
89    /// File info from the current log options.
90    fn file_info(&self) -> FileInfo {
91        FileInfo::new(
92            self.log_file_directory.clone().into(),
93            self.log_file_name.clone(),
94            self.log_file_max_size * MB_TO_BYTES,
95            self.log_file_max_files,
96        )
97    }
98
99    /// Initializes tracing with the configured options from cli args.
100    ///
101    /// Uses default layers for tracing. If you need to include custom layers,
102    /// use `init_tracing_with_layers` instead.
103    ///
104    /// Returns the file worker guard if a file worker was configured.
105    pub fn init_tracing(&self) -> eyre::Result<Option<FileWorkerGuard>> {
106        self.init_tracing_with_layers(Layers::new())
107    }
108
109    /// Initializes tracing with the configured options from cli args.
110    ///
111    /// Returns the file worker guard, and the file name, if a file worker was configured.
112    pub fn init_tracing_with_layers(
113        &self,
114        layers: Layers,
115    ) -> eyre::Result<Option<FileWorkerGuard>> {
116        let mut tracer = RethTracer::new();
117
118        let stdout = self.layer_info(self.log_stdout_format, self.log_stdout_filter.clone(), true);
119        tracer = tracer.with_stdout(stdout);
120
121        if self.journald {
122            tracer = tracer.with_journald(self.journald_filter.clone());
123        }
124
125        if self.log_file_max_files > 0 {
126            let info = self.file_info();
127            let file = self.layer_info(self.log_file_format, self.log_file_filter.clone(), false);
128            tracer = tracer.with_file(file, info);
129        }
130
131        let guard = tracer.init_with_layers(layers)?;
132        Ok(guard)
133    }
134}
135
136/// The color mode for the cli.
137#[derive(Debug, Copy, Clone, ValueEnum, Eq, PartialEq)]
138pub enum ColorMode {
139    /// Colors on
140    Always,
141    /// Colors on
142    Auto,
143    /// Colors off
144    Never,
145}
146
147impl Display for ColorMode {
148    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149        match self {
150            Self::Always => write!(f, "always"),
151            Self::Auto => write!(f, "auto"),
152            Self::Never => write!(f, "never"),
153        }
154    }
155}
156
157/// The verbosity settings for the cli.
158#[derive(Debug, Copy, Clone, Args)]
159#[command(next_help_heading = "Display")]
160pub struct Verbosity {
161    /// Set the minimum log level.
162    ///
163    /// -v      Errors
164    /// -vv     Warnings
165    /// -vvv    Info
166    /// -vvvv   Debug
167    /// -vvvvv  Traces (warning: very verbose!)
168    #[arg(short, long, action = ArgAction::Count, global = true, default_value_t = 3, verbatim_doc_comment, help_heading = "Display")]
169    verbosity: u8,
170
171    /// Silence all log output.
172    #[arg(long, alias = "silent", short = 'q', global = true, help_heading = "Display")]
173    quiet: bool,
174}
175
176impl Verbosity {
177    /// Get the corresponding [Directive] for the given verbosity, or none if the verbosity
178    /// corresponds to silent.
179    pub fn directive(&self) -> Directive {
180        if self.quiet {
181            LevelFilter::OFF.into()
182        } else {
183            let level = match self.verbosity - 1 {
184                0 => Level::ERROR,
185                1 => Level::WARN,
186                2 => Level::INFO,
187                3 => Level::DEBUG,
188                _ => Level::TRACE,
189            };
190
191            level.into()
192        }
193    }
194}