Skip to main content

elph_core/logger/
options.rs

1use std::path::PathBuf;
2
3/// How often log files are rotated.
4#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5pub enum LogRotation {
6    Hourly,
7    Daily,
8    Weekly,
9}
10
11impl LogRotation {
12    pub fn from_env(prefix: &str) -> Self {
13        let key = format!("{prefix}_LOG_ROTATION");
14        Self::parse(std::env::var(&key).ok().as_deref())
15    }
16
17    pub fn parse(value: Option<&str>) -> Self {
18        match value {
19            Some("hourly") => Self::Hourly,
20            Some("weekly") => Self::Weekly,
21            Some("daily") | None => Self::Daily,
22            _ => Self::Daily,
23        }
24    }
25}
26
27/// Resolved logging configuration for an application to initialize its subscriber.
28#[derive(Debug, Clone)]
29pub struct LoggingOptions {
30    pub app_name: &'static str,
31    pub logs_dir: PathBuf,
32    pub level: String,
33    pub rotation: LogRotation,
34    pub max_files: Option<usize>,
35    pub file_enabled: bool,
36    pub console_enabled: bool,
37}
38
39impl LoggingOptions {
40    pub fn level_from_env(prefix: &str) -> String {
41        let key = format!("{prefix}_LOG_LEVEL");
42        match std::env::var(&key) {
43            Ok(value) if matches!(value.as_str(), "trace" | "debug" | "info" | "warn" | "error") => value,
44            _ => "info".to_string(),
45        }
46    }
47
48    pub fn max_files_from_env(prefix: &str) -> Option<usize> {
49        let key = format!("{prefix}_LOG_MAX_FILES");
50        std::env::var(&key).ok().and_then(|value| value.parse().ok())
51    }
52
53    pub fn file_logging_enabled(prefix: &str) -> bool {
54        let key = format!("{prefix}_LOG_FILE");
55        std::env::var(&key).map(|value| value != "0").unwrap_or(true)
56    }
57
58    pub fn resolve(env_prefix: &str, app_name: &'static str, logs_dir: Option<PathBuf>, console_enabled: bool) -> Self {
59        let file_enabled = logs_dir.is_some() && Self::file_logging_enabled(env_prefix);
60        Self {
61            app_name,
62            logs_dir: logs_dir.unwrap_or_default(),
63            level: Self::level_from_env(env_prefix),
64            rotation: LogRotation::from_env(env_prefix),
65            max_files: Self::max_files_from_env(env_prefix),
66            file_enabled,
67            console_enabled,
68        }
69    }
70}
71
72#[cfg(test)]
73mod tests {
74    use super::*;
75
76    #[test]
77    fn defaults_to_daily_rotation() {
78        assert_eq!(LogRotation::parse(None), LogRotation::Daily);
79        assert_eq!(LogRotation::parse(Some("daily")), LogRotation::Daily);
80    }
81
82    #[test]
83    fn parses_rotation_values() {
84        assert_eq!(LogRotation::parse(Some("hourly")), LogRotation::Hourly);
85        assert_eq!(LogRotation::parse(Some("weekly")), LogRotation::Weekly);
86        assert_eq!(LogRotation::parse(Some("monthly")), LogRotation::Daily);
87    }
88}