Skip to main content

signal_kit/file_logging/
config.rs

1//! File logging configuration.
2//!
3//! This module provides configuration structures for file-based logging
4//! with rotation support.
5
6use serde::{Deserialize, Serialize};
7
8/// Configuration for file-based logging.
9///
10/// # Note
11///
12/// File logging is primarily intended for development and debugging.
13/// In production, ensure logs do not contain PII or sensitive data.
14///
15/// # Error Behavior
16///
17/// If file logging is enabled and cannot be initialized (e.g., invalid path,
18/// permission denied, unwritable directory), the application will **panic**
19/// with a clear error message. This fail-fast behavior ensures that logging
20/// issues are detected immediately rather than silently losing logs.
21#[derive(Debug, Clone, Serialize, Deserialize, Default)]
22#[non_exhaustive]
23pub struct FileLoggingConfig {
24    /// Whether file logging is enabled.
25    ///
26    /// Defaults to `false` - requires explicit opt-in.
27    #[serde(default)]
28    pub enabled: bool,
29
30    /// Full path to the log file (e.g., `/var/log/myapp/service.log`).
31    ///
32    /// Note: With `rolling::daily` or `rolling::hourly`, the actual log files
33    /// will have date suffixes (e.g., `service.2026-01-17`), not the exact
34    /// path specified here. This path is used to derive the directory and
35    /// filename prefix.
36    #[serde(default)]
37    pub file_path: String,
38
39    /// Log rotation settings.
40    #[serde(default)]
41    pub rotation: RotationConfig,
42}
43
44/// Log rotation configuration.
45#[derive(Debug, Clone, Serialize, Deserialize)]
46#[non_exhaustive]
47pub struct RotationConfig {
48    /// Rotation strategy.
49    #[serde(default)]
50    pub strategy: RotationStrategy,
51
52    /// Number of days to retain rotated log files.
53    ///
54    /// Only files matching the log filename pattern will be deleted.
55    #[serde(default = "default_retention_days")]
56    pub retention_days: u32,
57}
58
59const fn default_retention_days() -> u32 {
60    7
61}
62
63impl Default for RotationConfig {
64    fn default() -> Self {
65        Self {
66            strategy: RotationStrategy::default(),
67            retention_days: default_retention_days(),
68        }
69    }
70}
71
72impl RotationConfig {
73    /// Creates a daily rotation config with default retention.
74    pub const fn daily() -> Self {
75        Self {
76            strategy: RotationStrategy::Daily,
77            retention_days: default_retention_days(),
78        }
79    }
80
81    /// Creates an hourly rotation config with default retention.
82    pub const fn hourly() -> Self {
83        Self {
84            strategy: RotationStrategy::Hourly,
85            retention_days: default_retention_days(),
86        }
87    }
88
89    /// Creates a no-rotation config with default retention.
90    pub const fn never() -> Self {
91        Self {
92            strategy: RotationStrategy::Never,
93            retention_days: default_retention_days(),
94        }
95    }
96}
97
98/// Rotation strategy for log files.
99///
100/// `tracing_appender::rolling` creates files with date suffixes:
101/// - `Daily`: `service.2026-01-17`, `service.2026-01-16`, ...
102/// - `Hourly`: `service.2026-01-17.14`, `service.2026-01-17.13`, ...
103/// - `Never`: `service` (no rotation)
104#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
105#[serde(rename_all = "lowercase")]
106#[derive(Default)]
107pub enum RotationStrategy {
108    /// Rotate logs daily (creates `service.YYYY-MM-DD` files)
109    #[default]
110    Daily,
111    /// Rotate logs hourly (creates `service.YYYY-MM-DD.HH` files)
112    Hourly,
113    /// Do not rotate logs (creates a single `service` file)
114    Never,
115}
116
117impl RotationStrategy {
118    /// Returns the string representation of the strategy.
119    pub const fn as_str(self) -> &'static str {
120        match self {
121            Self::Daily => "daily",
122            Self::Hourly => "hourly",
123            Self::Never => "never",
124        }
125    }
126}
127
128impl FileLoggingConfig {
129    /// Returns a builder for constructing a `FileLoggingConfig`.
130    pub fn builder() -> FileLoggingConfigBuilder {
131        FileLoggingConfigBuilder::default()
132    }
133
134    /// Applies environment variable overrides to the configuration.
135    ///
136    /// Environment variables take precedence over values in the config struct.
137    ///
138    /// Supported environment variables:
139    /// - `SIGNAL_KIT_FILE_ENABLED`: "true", "false", "1", or "0"
140    /// - `SIGNAL_KIT_FILE_PATH`: Full path to the log file
141    /// - `SIGNAL_KIT_FILE_ROTATION`: "daily", "hourly", or "never"
142    /// - `SIGNAL_KIT_FILE_RETENTION_DAYS`: Number of days (u32)
143    pub fn with_env_overrides(mut self) -> Self {
144        if let Ok(val) = std::env::var("SIGNAL_KIT_FILE_ENABLED") {
145            self.enabled = parse_bool(&val).unwrap_or(self.enabled);
146        }
147        if let Ok(val) = std::env::var("SIGNAL_KIT_FILE_PATH")
148            && !val.trim().is_empty()
149        {
150            self.file_path = val;
151        }
152        if let Ok(val) = std::env::var("SIGNAL_KIT_FILE_ROTATION") {
153            self.rotation.strategy = match val.to_lowercase().as_str() {
154                "daily" => RotationStrategy::Daily,
155                "hourly" => RotationStrategy::Hourly,
156                "never" => RotationStrategy::Never,
157                _ => self.rotation.strategy, // Keep existing if invalid
158            };
159        }
160        if let Ok(val) = std::env::var("SIGNAL_KIT_FILE_RETENTION_DAYS") {
161            self.rotation.retention_days = val.parse().unwrap_or(self.rotation.retention_days);
162        }
163        self
164    }
165}
166
167/// Builder for `FileLoggingConfig`.
168#[derive(Debug, Default)]
169pub struct FileLoggingConfigBuilder {
170    enabled: bool,
171    file_path: Option<String>,
172    rotation: RotationConfig,
173}
174
175impl FileLoggingConfigBuilder {
176    /// Sets whether file logging is enabled.
177    pub fn enabled(mut self, enabled: bool) -> Self {
178        self.enabled = enabled;
179        self
180    }
181
182    /// Sets the log file path.
183    pub fn file_path(mut self, file_path: impl Into<String>) -> Self {
184        self.file_path = Some(file_path.into());
185        self
186    }
187
188    /// Sets the rotation configuration.
189    pub fn rotation(mut self, rotation: RotationConfig) -> Self {
190        self.rotation = rotation;
191        self
192    }
193
194    /// Builds the configuration, returning an error if enabled without a path.
195    pub fn build(self) -> Result<FileLoggingConfig, crate::file_logging::FileLoggingError> {
196        let file_path = self.file_path.unwrap_or_default();
197        if self.enabled && file_path.trim().is_empty() {
198            return Err(crate::file_logging::FileLoggingError::InvalidPath(
199                "file_path must be set when file logging is enabled".to_string(),
200            ));
201        }
202
203        Ok(FileLoggingConfig {
204            enabled: self.enabled,
205            file_path,
206            rotation: self.rotation,
207        })
208    }
209}
210
211/// Parses a boolean value from string, accepting "true"/"false" and "1"/"0".
212fn parse_bool(s: &str) -> Option<bool> {
213    match s.to_lowercase().as_str() {
214        "true" | "1" => Some(true),
215        "false" | "0" => Some(false),
216        _ => None,
217    }
218}
219
220#[cfg(test)]
221mod tests {
222    use super::*;
223
224    #[test]
225    fn test_default_file_logging_config() {
226        let config = FileLoggingConfig::default();
227        assert!(!config.enabled);
228        assert!(config.file_path.is_empty());
229        assert_eq!(config.rotation.strategy, RotationStrategy::Daily);
230        assert_eq!(config.rotation.retention_days, 7);
231    }
232
233    #[test]
234    fn test_default_rotation_config() {
235        let config = RotationConfig::default();
236        assert_eq!(config.strategy, RotationStrategy::Daily);
237        assert_eq!(config.retention_days, 7);
238    }
239
240    #[test]
241    fn test_rotation_strategy_as_str() {
242        assert_eq!(RotationStrategy::Daily.as_str(), "daily");
243        assert_eq!(RotationStrategy::Hourly.as_str(), "hourly");
244        assert_eq!(RotationStrategy::Never.as_str(), "never");
245    }
246
247    #[test]
248    fn test_parse_bool() {
249        assert_eq!(parse_bool("true"), Some(true));
250        assert_eq!(parse_bool("TRUE"), Some(true));
251        assert_eq!(parse_bool("1"), Some(true));
252        assert_eq!(parse_bool("false"), Some(false));
253        assert_eq!(parse_bool("FALSE"), Some(false));
254        assert_eq!(parse_bool("0"), Some(false));
255        assert_eq!(parse_bool("invalid"), None);
256        assert_eq!(parse_bool("2"), None);
257    }
258
259    #[test]
260    fn test_file_logging_config_with_env_overrides() {
261        // Test with no env vars set - should use defaults
262        let config = FileLoggingConfig::default();
263        let overridden = config.with_env_overrides();
264        assert!(!overridden.enabled);
265        assert!(overridden.file_path.is_empty());
266    }
267
268    #[test]
269    fn test_rotation_strategy_serde_roundtrip() {
270        let strategies = [
271            RotationStrategy::Daily,
272            RotationStrategy::Hourly,
273            RotationStrategy::Never,
274        ];
275
276        for strategy in strategies {
277            let serialized = serde_json::to_string(&strategy).unwrap();
278            let deserialized: RotationStrategy = serde_json::from_str(&serialized).unwrap();
279            assert_eq!(strategy, deserialized);
280        }
281    }
282
283    #[test]
284    fn test_file_logging_config_serde_roundtrip() {
285        let config = FileLoggingConfig {
286            enabled: true,
287            file_path: "/var/log/test.log".to_string(),
288            rotation: RotationConfig {
289                strategy: RotationStrategy::Hourly,
290                retention_days: 14,
291            },
292        };
293
294        let serialized = serde_json::to_string(&config).unwrap();
295        let deserialized: FileLoggingConfig = serde_json::from_str(&serialized).unwrap();
296
297        assert_eq!(deserialized.enabled, config.enabled);
298        assert_eq!(deserialized.file_path, config.file_path);
299        assert_eq!(deserialized.rotation.strategy, config.rotation.strategy);
300        assert_eq!(
301            deserialized.rotation.retention_days,
302            config.rotation.retention_days
303        );
304    }
305}