brinkhaustools/
logging.rsuse 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;
pub struct RingBuffer {
lines: Mutex<VecDeque<String>>,
max_lines: usize,
}
impl RingBuffer {
pub fn new(max_lines: usize) -> Self {
Self {
lines: Mutex::new(VecDeque::with_capacity(max_lines)),
max_lines,
}
}
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);
}
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
}
pub fn len(&self) -> usize {
self.lines.lock().unwrap().len()
}
pub fn is_empty(&self) -> bool {
self.lines.lock().unwrap().is_empty()
}
}
pub struct LoggingConfig {
pub log_dir: PathBuf,
pub max_bytes: u64,
pub backup_count: usize,
pub ring_buffer_size: usize,
pub level: log::LevelFilter,
pub console: bool,
}
impl Default for LoggingConfig {
fn default() -> Self {
Self {
log_dir: PathBuf::from("data/logs"),
max_bytes: 10 * 1024 * 1024, backup_count: 50,
ring_buffer_size: 1000,
level: log::LevelFilter::Info,
console: true,
}
}
}
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 {
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,
})
}
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)
}
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);
}
}
pub fn get_ring_buffer(&self) -> String {
self.ring_buffer.get()
}
pub fn ring_buffer(&self) -> &Arc<RingBuffer> {
&self.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);
drop(file_guard);
self.rotate();
}
}
}
}
fn rotate(&self) {
let log_path = self.log_dir.join("applicationLog.txt");
{
let mut file_guard = self.log_file.lock().unwrap();
*file_guard = None;
}
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"));
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;
}
}
}
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"));
}
#[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"));
}
#[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"));
}
}