Skip to main content

fbc_starter/
logging.rs

1use std::fs;
2use std::path::PathBuf;
3
4/// 清理超过限制的旧日志文件
5pub fn cleanup_old_logs(
6    directory: &str,
7    filename: &str,
8    count_limit: u32,
9) -> Result<(), std::io::Error> {
10    if count_limit == 0 {
11        return Ok(()); // 0 表示不限制
12    }
13
14    let dir_path = PathBuf::from(directory);
15    if !dir_path.exists() {
16        return Ok(());
17    }
18
19    // 获取所有符合模式的日志文件
20    let mut log_files: Vec<(u32, PathBuf)> = Vec::new();
21    
22    if let Ok(entries) = fs::read_dir(&dir_path) {
23        for entry in entries {
24            if let Ok(entry) = entry {
25                if let Some(name) = entry.file_name().to_str() {
26                    // 主日志文件
27                    if name == format!("{}.log", filename) {
28                        log_files.push((0, entry.path()));
29                    }
30                    // 备份文件格式: app.log.1, app.log.2, app.log.2026-02-06, 等
31                    if name.starts_with(&format!("{}.", filename)) || name.starts_with(&format!("{}-", filename)) {
32                        if let Some(index_str) = name.strip_prefix(&format!("{}.", filename)) {
33                            // 尝试解析数字索引
34                            if let Ok(index) = index_str.parse::<u32>() {
35                                log_files.push((index, entry.path()));
36                            }
37                        }
38                    }
39                }
40            }
41        }
42    }
43
44    // 按索引排序,保留最新的 count_limit 个
45    log_files.sort_by_key(|k| k.0);
46    
47    if log_files.len() > count_limit as usize {
48        let to_delete = log_files.len() - count_limit as usize;
49        for (_, path) in log_files.iter().take(to_delete) {
50            let _ = fs::remove_file(path);
51        }
52    }
53
54    Ok(())
55}
56
57/// 检查日志文件大小并返回是否超过限制
58pub fn check_log_file_size(
59    directory: &str,
60    filename: &str,
61    size_limit_mb: u64,
62) -> Result<bool, std::io::Error> {
63    if size_limit_mb == 0 {
64        return Ok(false); // 0 表示不限制
65    }
66
67    let log_path = PathBuf::from(directory).join(format!("{}.log", filename));
68    
69    if log_path.exists() {
70        let size_bytes = fs::metadata(&log_path)?.len();
71        let size_mb = size_bytes / (1024 * 1024);
72        Ok(size_mb > size_limit_mb)
73    } else {
74        Ok(false)
75    }
76}
77