|
| 1 | +use std::path::Path; |
| 2 | + |
| 3 | +use derive_more::FromStr; |
| 4 | +use serde::{Deserialize, Serialize}; |
| 5 | +use serde_with::{DeserializeFromStr, SerializeDisplay}; |
| 6 | +use tracing_appender::{non_blocking, rolling}; |
| 7 | +use tracing_subscriber::{fmt, layer::SubscriberExt, util::SubscriberInitExt, Layer}; |
| 8 | + |
| 9 | +/// `RUST_LOG` statement used by default in file logging. |
| 10 | +// rustyline is annoying |
| 11 | +pub(crate) const DEFAULT_FILE_RUST_LOG: &str = "rustyline=warn,debug"; |
| 12 | + |
| 13 | +/// Initialize logging both in the terminal and file based. |
| 14 | +/// |
| 15 | +/// The terminal based logging layer will: |
| 16 | +/// - use the default [`fmt::format::Format`]. |
| 17 | +/// - log to [`std::io::Stderr`] |
| 18 | +/// |
| 19 | +/// The file base logging layer will: |
| 20 | +/// - use the default [`fmt::format::Format`] save for: |
| 21 | +/// - including line numbers. |
| 22 | +/// - not using ansi colors. |
| 23 | +/// - create log files in the `logs` dir inside the given `iroh_data_root`. |
| 24 | +/// - rotate files every [`Self::rotation`]. |
| 25 | +/// - keep at most [`Self::max_files`] log files. |
| 26 | +/// - use the filtering defined by [`Self::rust_log`]. When not provided, the default |
| 27 | +/// [`DEFAULT_FILE_RUST_LOG`] is used. |
| 28 | +/// - create log files with the name `iroh-<ROTATION_BASED_NAME>.log` (ex: iroh-2024-02-02.log) |
| 29 | +pub(crate) fn init_terminal_and_file_logging( |
| 30 | + file_log_config: &FileLogging, |
| 31 | + logs_dir: &Path, |
| 32 | +) -> anyhow::Result<non_blocking::WorkerGuard> { |
| 33 | + let terminal_layer = fmt::layer() |
| 34 | + .with_writer(std::io::stderr) |
| 35 | + .with_filter(tracing_subscriber::EnvFilter::from_default_env()); |
| 36 | + let (file_layer, guard) = { |
| 37 | + let FileLogging { |
| 38 | + rust_log, |
| 39 | + max_files, |
| 40 | + rotation, |
| 41 | + } = file_log_config; |
| 42 | + |
| 43 | + let filter = rust_log.layer(); |
| 44 | + |
| 45 | + let (file_logger, guard) = { |
| 46 | + let file_appender = if *max_files == 0 || &filter.to_string() == "off" { |
| 47 | + fmt::writer::OptionalWriter::none() |
| 48 | + } else { |
| 49 | + let rotation = match rotation { |
| 50 | + Rotation::Hourly => rolling::Rotation::HOURLY, |
| 51 | + Rotation::Daily => rolling::Rotation::DAILY, |
| 52 | + Rotation::Never => rolling::Rotation::NEVER, |
| 53 | + }; |
| 54 | + let logs_path = logs_dir.join("logs"); |
| 55 | + |
| 56 | + let file_appender = rolling::Builder::new() |
| 57 | + .rotation(rotation) |
| 58 | + .max_log_files(*max_files) |
| 59 | + .filename_prefix("iroh") |
| 60 | + .filename_suffix("log") |
| 61 | + .build(logs_path)?; |
| 62 | + fmt::writer::OptionalWriter::some(file_appender) |
| 63 | + }; |
| 64 | + non_blocking(file_appender) |
| 65 | + }; |
| 66 | + |
| 67 | + let layer = fmt::Layer::new() |
| 68 | + .with_ansi(false) |
| 69 | + .with_line_number(true) |
| 70 | + .with_writer(file_logger) |
| 71 | + .with_filter(filter); |
| 72 | + (layer, guard) |
| 73 | + }; |
| 74 | + tracing_subscriber::registry() |
| 75 | + .with(file_layer) |
| 76 | + .with(terminal_layer) |
| 77 | + .try_init()?; |
| 78 | + Ok(guard) |
| 79 | +} |
| 80 | + |
| 81 | +/// Initialize logging in the terminal. |
| 82 | +/// |
| 83 | +/// This will: |
| 84 | +/// - use the default [`fmt::format::Format`]. |
| 85 | +/// - log to [`std::io::Stderr`] |
| 86 | +pub(crate) fn init_terminal_logging() -> anyhow::Result<()> { |
| 87 | + let terminal_layer = fmt::layer() |
| 88 | + .with_writer(std::io::stderr) |
| 89 | + .with_filter(tracing_subscriber::EnvFilter::from_default_env()); |
| 90 | + tracing_subscriber::registry() |
| 91 | + .with(terminal_layer) |
| 92 | + .try_init()?; |
| 93 | + Ok(()) |
| 94 | +} |
| 95 | + |
| 96 | +#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] |
| 97 | +#[serde(default)] |
| 98 | +pub(crate) struct FileLogging { |
| 99 | + /// RUST_LOG directive to filter file logs. |
| 100 | + pub(crate) rust_log: EnvFilter, |
| 101 | + /// Maximum number of files to keep. |
| 102 | + pub(crate) max_files: usize, |
| 103 | + /// How often should a new log file be produced. |
| 104 | + pub(crate) rotation: Rotation, |
| 105 | +} |
| 106 | + |
| 107 | +impl Default for FileLogging { |
| 108 | + fn default() -> Self { |
| 109 | + Self { |
| 110 | + rust_log: EnvFilter::default(), |
| 111 | + max_files: 4, |
| 112 | + rotation: Rotation::default(), |
| 113 | + } |
| 114 | + } |
| 115 | +} |
| 116 | + |
| 117 | +/// Wrapper to obtain a [`tracing_subscriber::EnvFilter`] that satisfies required bounds. |
| 118 | +#[derive( |
| 119 | + Debug, Clone, PartialEq, Eq, SerializeDisplay, DeserializeFromStr, derive_more::Display, |
| 120 | +)] |
| 121 | +#[display("{_0}")] |
| 122 | +pub(crate) struct EnvFilter(String); |
| 123 | + |
| 124 | +impl FromStr for EnvFilter { |
| 125 | + type Err = <tracing_subscriber::EnvFilter as FromStr>::Err; |
| 126 | + |
| 127 | + fn from_str(s: &str) -> Result<Self, Self::Err> { |
| 128 | + // validate the RUST_LOG statement |
| 129 | + let _valid_env = tracing_subscriber::EnvFilter::from_str(s)?; |
| 130 | + Ok(EnvFilter(s.into())) |
| 131 | + } |
| 132 | +} |
| 133 | + |
| 134 | +impl Default for EnvFilter { |
| 135 | + fn default() -> Self { |
| 136 | + Self(DEFAULT_FILE_RUST_LOG.into()) |
| 137 | + } |
| 138 | +} |
| 139 | + |
| 140 | +impl EnvFilter { |
| 141 | + pub(crate) fn layer(&self) -> tracing_subscriber::EnvFilter { |
| 142 | + tracing_subscriber::EnvFilter::from_str(&self.0).expect("validated RUST_LOG statement") |
| 143 | + } |
| 144 | +} |
| 145 | + |
| 146 | +/// How often should a new file be created for file logs. |
| 147 | +/// |
| 148 | +/// Akin to [`tracing_appender::rolling::Rotation`]. |
| 149 | +#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, Default)] |
| 150 | +#[serde(rename_all = "lowercase")] |
| 151 | +pub(crate) enum Rotation { |
| 152 | + #[default] |
| 153 | + Hourly, |
| 154 | + Daily, |
| 155 | + Never, |
| 156 | +} |
| 157 | + |
| 158 | +#[cfg(test)] |
| 159 | +mod tests { |
| 160 | + use super::*; |
| 161 | + |
| 162 | + /// Tests that the default file logging `RUST_LOG` statement produces a valid layer. |
| 163 | + #[test] |
| 164 | + fn test_default_file_rust_log() { |
| 165 | + let _ = EnvFilter::default().layer(); |
| 166 | + } |
| 167 | +} |
0 commit comments