brinkhaustools/
logging.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
use std::collections::VecDeque;
use std::fs;
use std::io::Write as IoWrite;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};

use crate::error::Result;

/// Thread-safe ring buffer that keeps the last N log lines.
pub struct RingBuffer {
    lines: Mutex<VecDeque<String>>,
    max_lines: usize,
}

impl RingBuffer {
    /// Create a ring buffer with the given maximum capacity.
    pub fn new(max_lines: usize) -> Self {
        Self {
            lines: Mutex::new(VecDeque::with_capacity(max_lines)),
            max_lines,
        }
    }

    /// Push a line into the buffer. If full, the oldest line is evicted.
    pub fn push(&self, line: String) {
        let mut lines = self.lines.lock().unwrap();
        if lines.len() >= self.max_lines {
            lines.pop_front();
        }
        lines.push_back(line);
    }

    /// Get all lines as a single string separated by newlines.
    pub fn get(&self) -> String {
        let lines = self.lines.lock().unwrap();
        let mut result = String::new();
        for line in lines.iter() {
            result.push_str(line);
            result.push('\n');
        }
        result
    }

    /// Get the number of lines currently in the buffer.
    pub fn len(&self) -> usize {
        self.lines.lock().unwrap().len()
    }

    /// Check if the buffer is empty.
    pub fn is_empty(&self) -> bool {
        self.lines.lock().unwrap().is_empty()
    }
}

/// Configuration for the LoggingHelper.
pub struct LoggingConfig {
    /// Directory for log files.
    pub log_dir: PathBuf,
    /// Maximum size of a single log file in bytes.
    pub max_bytes: u64,
    /// Number of backup files to keep.
    pub backup_count: usize,
    /// Maximum number of lines in the ring buffer.
    pub ring_buffer_size: usize,
    /// Log level filter.
    pub level: log::LevelFilter,
    /// Mirror every log line to the console (stdout) in addition to the file and
    /// ring buffer. Enabled by default; turn off for headless/service operation.
    pub console: bool,
}

impl Default for LoggingConfig {
    fn default() -> Self {
        Self {
            log_dir: PathBuf::from("data/logs"),
            max_bytes: 10 * 1024 * 1024, // 10 MB
            backup_count: 50,
            ring_buffer_size: 1000,
            level: log::LevelFilter::Info,
            console: true,
        }
    }
}

/// Centralized logging with rotating file handler and in-memory ring buffer.
pub struct LoggingHelper {
    ring_buffer: Arc<RingBuffer>,
    log_dir: PathBuf,
    log_file: Mutex<Option<fs::File>>,
    max_bytes: u64,
    backup_count: usize,
    current_size: Mutex<u64>,
    console: bool,
    level: log::LevelFilter,
}

impl LoggingHelper {
    /// Create a new LoggingHelper and set up logging infrastructure.
    pub fn new(config: LoggingConfig) -> Result<Self> {
        fs::create_dir_all(&config.log_dir)
            .map_err(|e| crate::error::Error::Logging(format!("Failed to create log dir: {}", e)))?;

        let log_path = config.log_dir.join("applicationLog.txt");
        let current_size = if log_path.exists() {
            fs::metadata(&log_path).map(|m| m.len()).unwrap_or(0)
        } else {
            0
        };

        let file = fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(&log_path)
            .map_err(|e| crate::error::Error::Logging(format!("Failed to open log file: {}", e)))?;

        Ok(Self {
            ring_buffer: Arc::new(RingBuffer::new(config.ring_buffer_size)),
            log_dir: config.log_dir,
            log_file: Mutex::new(Some(file)),
            max_bytes: config.max_bytes,
            backup_count: config.backup_count,
            current_size: Mutex::new(current_size),
            console: config.console,
            level: config.level,
        })
    }

    /// Build a `LoggingHelper` from `config` and install it as the global `log`
    /// backend (`log::set_boxed_logger` + `set_max_level`). Returns the shared
    /// handle; keep it alive for ring-buffer/file access. After this call every
    /// `log::info!`/`warn!`/`error!` in the process is routed to the file, the
    /// ring buffer and — unless disabled — the console.
    ///
    /// Fails if a global logger was already installed (the `log` crate permits
    /// exactly one) or the log directory/file cannot be opened.
    pub fn install(config: LoggingConfig) -> Result<Arc<LoggingHelper>> {
        let level = config.level;
        let helper = Arc::new(LoggingHelper::new(config)?);
        log::set_boxed_logger(Box::new(LogAdapter(Arc::clone(&helper))))
            .map_err(|e| crate::error::Error::Logging(format!("Failed to install logger: {}", e)))?;
        log::set_max_level(level);
        Ok(helper)
    }

    /// Format and write a single log record to the file, the ring buffer and
    /// (when enabled) the console. Used by the `log::Log` adapter.
    pub fn record(&self, record: &log::Record) {
        let line = format!(
            "{} {:<5} [{}] {}",
            chrono::Local::now().format("%Y-%m-%d %H:%M:%S%.3f"),
            record.level(),
            record.target(),
            record.args()
        );
        self.write_line(&line);
        if self.console {
            println!("{}", line);
        }
    }

    /// Get the ring buffer contents as a string.
    pub fn get_ring_buffer(&self) -> String {
        self.ring_buffer.get()
    }

    /// Get a reference to the ring buffer for direct access.
    pub fn ring_buffer(&self) -> &Arc<RingBuffer> {
        &self.ring_buffer
    }

    /// Write a log line to both file and ring buffer.
    pub fn write_line(&self, line: &str) {
        self.ring_buffer.push(line.to_string());

        let mut file_guard = self.log_file.lock().unwrap();
        if let Some(ref mut file) = *file_guard {
            let bytes = format!("{}\n", line);
            if file.write_all(bytes.as_bytes()).is_ok() {
                let mut size = self.current_size.lock().unwrap();
                *size += bytes.len() as u64;
                if *size >= self.max_bytes {
                    drop(size);
                    // Rotate
                    drop(file_guard);
                    self.rotate();
                }
            }
        }
    }

    fn rotate(&self) {
        let log_path = self.log_dir.join("applicationLog.txt");

        // Close current file
        {
            let mut file_guard = self.log_file.lock().unwrap();
            *file_guard = None;
        }

        // Shift backups
        for i in (1..self.backup_count).rev() {
            let from = self.log_dir.join(format!("applicationLog.txt.{}", i));
            let to = self.log_dir.join(format!("applicationLog.txt.{}", i + 1));
            let _ = fs::rename(&from, &to);
        }
        let _ = fs::rename(&log_path, self.log_dir.join("applicationLog.txt.1"));

        // Open new file
        if let Ok(file) = fs::File::create(&log_path) {
            let mut file_guard = self.log_file.lock().unwrap();
            *file_guard = Some(file);
            *self.current_size.lock().unwrap() = 0;
        }
    }
}

/// Adapter that turns a shared [`LoggingHelper`] into a global `log` backend.
/// Registered via [`LoggingHelper::install`]; the held `Arc` keeps the helper
/// (and thus the ring buffer / open file) alive for the process lifetime.
struct LogAdapter(Arc<LoggingHelper>);

impl log::Log for LogAdapter {
    fn enabled(&self, metadata: &log::Metadata) -> bool {
        metadata.level() <= self.0.level
    }

    fn log(&self, record: &log::Record) {
        if self.enabled(record.metadata()) {
            self.0.record(record);
        }
    }

    fn flush(&self) {
        if let Some(ref mut file) = *self.0.log_file.lock().unwrap() {
            let _ = file.flush();
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_ring_buffer_capacity() {
        let buf = RingBuffer::new(5);
        for i in 0..7 {
            buf.push(format!("line {}", i));
        }
        assert_eq!(buf.len(), 5);
        let contents = buf.get();
        assert!(!contents.contains("line 0"));
        assert!(!contents.contains("line 1"));
        assert!(contents.contains("line 2"));
        assert!(contents.contains("line 6"));
    }

    #[test]
    fn test_ring_buffer_empty() {
        let buf = RingBuffer::new(10);
        assert_eq!(buf.get(), "");
        assert!(buf.is_empty());
    }

    #[test]
    fn test_ring_buffer_exact_capacity() {
        let buf = RingBuffer::new(3);
        buf.push("a".to_string());
        buf.push("b".to_string());
        buf.push("c".to_string());
        assert_eq!(buf.len(), 3);
        let contents = buf.get();
        assert!(contents.contains("a"));
        assert!(contents.contains("b"));
        assert!(contents.contains("c"));
    }

    #[test]
    fn test_logging_helper_creates_dir() {
        let dir = tempfile::tempdir().unwrap();
        let log_dir = dir.path().join("subdir").join("logs");
        let config = LoggingConfig {
            log_dir: log_dir.clone(),
            ..Default::default()
        };
        let _helper = LoggingHelper::new(config).unwrap();
        assert!(log_dir.exists());
    }

    #[test]
    fn test_logging_helper_ring_buffer() {
        let dir = tempfile::tempdir().unwrap();
        let config = LoggingConfig {
            log_dir: dir.path().to_path_buf(),
            ..Default::default()
        };
        let helper = LoggingHelper::new(config).unwrap();
        helper.write_line("test message 1");
        helper.write_line("test message 2");
        let buffer = helper.get_ring_buffer();
        assert!(buffer.contains("test message 1"));
        assert!(buffer.contains("test message 2"));
    }

    #[test]
    fn test_logging_helper_file_output() {
        let dir = tempfile::tempdir().unwrap();
        let config = LoggingConfig {
            log_dir: dir.path().to_path_buf(),
            ..Default::default()
        };
        let helper = LoggingHelper::new(config).unwrap();
        helper.write_line("file test line");
        drop(helper);
        let log_path = dir.path().join("applicationLog.txt");
        let contents = fs::read_to_string(log_path).unwrap();
        assert!(contents.contains("file test line"));
    }

    // Routing of a `log::Record` to file + ring buffer, without touching the
    // global logger (deterministic, repeatable). Console is disabled so the test
    // produces no stdout noise.
    #[test]
    fn test_record_routes_to_file_and_ring() {
        let dir = tempfile::tempdir().unwrap();
        let config = LoggingConfig {
            log_dir: dir.path().to_path_buf(),
            console: false,
            ..Default::default()
        };
        let helper = LoggingHelper::new(config).unwrap();
        helper.record(
            &log::Record::builder()
                .args(format_args!("routed message"))
                .level(log::Level::Warn)
                .target("unit")
                .build(),
        );
        let buffer = helper.get_ring_buffer();
        assert!(buffer.contains("routed message"));
        assert!(buffer.contains("WARN"));
        assert!(buffer.contains("[unit]"));
        drop(helper);
        let contents = fs::read_to_string(dir.path().join("applicationLog.txt")).unwrap();
        assert!(contents.contains("routed message"));
    }

    // Installing as the global backend routes the `log::*` macros. This is the
    // only test that touches the process-global logger (the `log` crate allows a
    // single registration).
    #[test]
    fn test_install_routes_log_macros() {
        let dir = tempfile::tempdir().unwrap();
        let config = LoggingConfig {
            log_dir: dir.path().to_path_buf(),
            console: false,
            ..Default::default()
        };
        let helper = LoggingHelper::install(config).expect("install global logger");
        log::info!(target: "unit", "macro routed line");
        log::logger().flush();
        assert!(helper.get_ring_buffer().contains("macro routed line"));
    }
}