Skip to main content

signal_kit/file_logging/
mod.rs

1//! File-based logging for the signal-kit crate.
2//!
3//! This module provides file-based logging capabilities as a composable
4//! layer for the tracing subscriber. It supports time-based log rotation
5//! and automatic cleanup of old log files.
6
7mod config;
8#[cfg(feature = "file-logging")]
9mod rotation;
10
11pub use config::{FileLoggingConfig, FileLoggingConfigBuilder, RotationConfig, RotationStrategy};
12
13use std::io;
14#[cfg(feature = "file-logging")]
15use std::path::Path;
16#[cfg(feature = "file-logging")]
17use tracing_appender::non_blocking::{NonBlocking, WorkerGuard};
18
19#[cfg(feature = "file-logging")]
20use rotation::{cleanup_old_logs, create_rolling_appender, split_dir_and_prefix};
21
22/// Errors that can occur during file logging initialization.
23///
24/// Note: `Disabled` is not an error - use `Ok(None)` to indicate disabled.
25#[derive(Debug, thiserror::Error)]
26pub enum FileLoggingError {
27    /// Invalid log file path provided.
28    #[error("invalid log file path: {0}")]
29    InvalidPath(String),
30
31    /// IO error occurred during file logging operations.
32    #[error("IO error: {0}")]
33    Io(#[from] io::Error),
34
35    /// File logging was enabled in configuration, but the `file-logging`
36    /// cargo feature is not compiled into this build of signal-kit.
37    #[error(
38        "file logging was enabled in FileLoggingConfig, but the `file-logging` cargo feature is not enabled for signal-kit; add `features = [\"file-logging\"]` to the signal-kit dependency"
39    )]
40    FeatureDisabled,
41}
42
43/// Builds a file logging writer and guard.
44///
45/// This returns the non-blocking writer and worker guard, allowing the
46/// fmt layer to be constructed inline with proper type inference.
47///
48/// # Arguments
49///
50/// * `config` - File logging configuration
51///
52/// # Returns
53///
54/// - `Ok(Some((writer, guard)))` - File logging enabled
55/// - `Ok(None)` - File logging disabled
56/// - `Err(e)` - Configuration error
57#[cfg(feature = "file-logging")]
58pub fn build_file_writer(
59    config: &FileLoggingConfig,
60) -> Result<Option<(NonBlocking, WorkerGuard)>, FileLoggingError> {
61    if !config.enabled {
62        return Ok(None);
63    }
64
65    if config.file_path.is_empty() {
66        return Err(FileLoggingError::InvalidPath(
67            "file_path must be set when file logging is enabled".to_string(),
68        ));
69    }
70
71    let file_path = Path::new(&config.file_path);
72    let appender = create_rolling_appender(file_path, config.rotation.strategy)?;
73    let (dir, prefix) = split_dir_and_prefix(file_path)?;
74
75    // Cleanup old logs
76    let _ = cleanup_old_logs(
77        &dir,
78        &prefix,
79        config.rotation.strategy,
80        config.rotation.retention_days,
81    );
82
83    let (non_blocking, guard) = tracing_appender::non_blocking(appender);
84
85    Ok(Some((non_blocking, guard)))
86}
87
88#[cfg(all(test, feature = "file-logging"))]
89mod tests {
90    use super::*;
91    use std::fs;
92    use tempfile::TempDir;
93
94    #[test]
95    fn test_build_file_writer_returns_none_when_disabled() {
96        let config = FileLoggingConfig {
97            enabled: false,
98            ..Default::default()
99        };
100
101        let result = build_file_writer(&config).unwrap();
102        assert!(result.is_none());
103    }
104
105    #[test]
106    fn test_build_file_writer_errors_with_empty_path() {
107        let config = FileLoggingConfig {
108            enabled: true,
109            file_path: String::new(),
110            ..Default::default()
111        };
112
113        let result = build_file_writer(&config);
114        assert!(result.is_err());
115        assert!(matches!(result, Err(FileLoggingError::InvalidPath(_))));
116    }
117
118    #[test]
119    fn test_build_file_writer_creates_writer() {
120        let temp_dir = TempDir::new().unwrap();
121        let log_path = temp_dir.path().join("test.log");
122
123        let config = FileLoggingConfig {
124            enabled: true,
125            file_path: log_path.to_str().unwrap().to_string(),
126            rotation: RotationConfig {
127                strategy: RotationStrategy::Never,
128                retention_days: 0,
129            },
130        };
131
132        let result = build_file_writer(&config);
133        assert!(result.is_ok());
134        assert!(result.unwrap().is_some());
135
136        // The file should be created when the layer starts writing
137        // (This is a basic check that the writer was created)
138    }
139
140    #[test]
141    fn test_cleanup_old_logs_safe_pattern_matching() {
142        let temp_dir = TempDir::new().unwrap();
143
144        // Create various files to test pattern matching safety
145        fs::write(temp_dir.path().join("service.2026-01-17"), "log1").unwrap();
146        fs::write(temp_dir.path().join("service.2026-01-16"), "log2").unwrap();
147        fs::write(temp_dir.path().join("service.2026-01-15"), "log3").unwrap();
148
149        // Create files that should NOT be deleted
150        fs::write(temp_dir.path().join("service.2026-01-17.backup"), "backup").unwrap();
151        fs::write(temp_dir.path().join("service.2026-01-17.gz"), "gz").unwrap();
152        fs::write(temp_dir.path().join("other.2026-01-17"), "other").unwrap();
153        fs::write(temp_dir.path().join("service_bak.log"), "bak").unwrap();
154
155        // Run cleanup with 1 day retention (should delete files older than 1 day)
156        // We need to make the old files actually old by setting their modification time
157        // For this test, we'll just verify the pattern matching logic
158
159        let entries = fs::read_dir(temp_dir.path()).unwrap();
160        let matching_files: Vec<_> = entries
161            .flatten()
162            .filter_map(|e| e.file_name().into_string().ok())
163            .filter(|n| rotation::matches_log_pattern_strict(n, "service", RotationStrategy::Daily))
164            .collect();
165
166        // Should only match the exact daily rotation files
167        assert_eq!(matching_files.len(), 3);
168        assert!(matching_files.contains(&"service.2026-01-17".to_string()));
169        assert!(matching_files.contains(&"service.2026-01-16".to_string()));
170        assert!(matching_files.contains(&"service.2026-01-15".to_string()));
171    }
172
173    #[test]
174    fn test_build_file_writer_disabled_returns_none() {
175        let config = FileLoggingConfig {
176            enabled: false,
177            ..Default::default()
178        };
179
180        let result = build_file_writer(&config).unwrap();
181        assert!(result.is_none());
182    }
183
184    #[test]
185    fn test_build_file_writer_empty_path_errors() {
186        let config = FileLoggingConfig {
187            enabled: true,
188            file_path: String::new(),
189            ..Default::default()
190        };
191
192        let result = build_file_writer(&config);
193        assert!(result.is_err());
194        assert!(matches!(result, Err(FileLoggingError::InvalidPath(_))));
195    }
196
197    #[test]
198    fn test_build_file_writer_returns_writer_and_guard() {
199        let temp_dir = TempDir::new().unwrap();
200        let log_path = temp_dir.path().join("test.log");
201
202        let config = FileLoggingConfig {
203            enabled: true,
204            file_path: log_path.to_str().unwrap().to_string(),
205            rotation: RotationConfig {
206                strategy: RotationStrategy::Never,
207                retention_days: 0,
208            },
209        };
210
211        let result = build_file_writer(&config);
212        assert!(result.is_ok());
213        let option = result.unwrap();
214        assert!(option.is_some());
215        let (_writer, _guard) = option.unwrap();
216
217        // The guard keeps the appender alive
218        // Dropping the guard would flush logs
219    }
220}