clap_logflag/
config.rs

1use std::path::PathBuf;
2
3/// This enum represents the whole logging configuration,
4/// including all logging destinations and their respective log level filters.
5#[derive(Debug, Clone, PartialEq, Eq)]
6pub struct LoggingConfig {
7    /// List of destinations to log to.
8    /// If the list of destinations is empty, logging is disabled.
9    destinations: Vec<LogDestinationConfig>,
10}
11
12impl LoggingConfig {
13    /// Create a new [LoggingConfig] with the given destinations.
14    ///
15    /// If the list of destinations is empty, logging is disabled.
16    pub fn new(destinations: Vec<LogDestinationConfig>) -> Self {
17        Self { destinations }
18    }
19
20    /// Create a [LoggingConfig] that disables logging.
21    pub fn disabled() -> Self {
22        Self {
23            destinations: vec![],
24        }
25    }
26
27    /// Get the list of destinations to log to.
28    pub fn destinations(&self) -> &[LogDestinationConfig] {
29        &self.destinations
30    }
31}
32
33/// Configuration for a log destination, containing the destination and the log level.
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub struct LogDestinationConfig {
36    /// The destination to log to.
37    pub destination: LogDestination,
38
39    /// Only log messages at this level or higher to this destination.
40    ///
41    /// If `None`, the default level is used.
42    pub level: Option<log::LevelFilter>,
43}
44
45/// A destination that can be logged to, e.g. a file or the system log.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub enum LogDestination {
48    /// Log to stderr
49    Stderr,
50
51    /// Log to the file at the given path
52    File(PathBuf),
53
54    /// Log to the system log
55    Syslog,
56}
57
58#[cfg(test)]
59mod tests {
60    use super::*;
61
62    #[test]
63    fn disabled() {
64        let config = LoggingConfig::disabled();
65        assert!(config.destinations().is_empty());
66    }
67
68    #[test]
69    fn new() {
70        let config = LoggingConfig::new(vec![
71            LogDestinationConfig {
72                destination: LogDestination::Stderr,
73                level: Some(log::LevelFilter::Info),
74            },
75            LogDestinationConfig {
76                destination: LogDestination::File(PathBuf::from("/tmp/logfile")),
77                level: Some(log::LevelFilter::Debug),
78            },
79        ]);
80        assert_eq!(
81            vec![
82                LogDestinationConfig {
83                    destination: LogDestination::Stderr,
84                    level: Some(log::LevelFilter::Info),
85                },
86                LogDestinationConfig {
87                    destination: LogDestination::File(PathBuf::from("/tmp/logfile")),
88                    level: Some(log::LevelFilter::Debug),
89                },
90            ],
91            config.destinations()
92        );
93    }
94}