acme_disk_use/
logger.rs

1use std::fs::OpenOptions;
2use std::io::Write;
3
4/// Initialize the logger to write to a file
5///
6/// Logs will be written to `app.log` in the current directory.
7/// The log file is automatically added to .gitignore.
8///
9/// Log level can be controlled via RUST_LOG environment variable:
10/// - RUST_LOG=debug cargo run (shows all debug and higher)
11/// - RUST_LOG=info cargo run (shows info and higher, default)
12/// - RUST_LOG=warn cargo run (shows warnings and errors only)
13pub fn init() -> Result<(), Box<dyn std::error::Error>> {
14    let log_file = OpenOptions::new()
15        .create(true)
16        .append(true)
17        .open("app.log")?;
18
19    env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info"))
20        .format(|buf, record| {
21            use std::time::SystemTime;
22
23            // Get current timestamp
24            let now = SystemTime::now()
25                .duration_since(SystemTime::UNIX_EPOCH)
26                .unwrap();
27            let secs = now.as_secs();
28
29            // Format: [TIMESTAMP] LEVEL - MESSAGE
30            writeln!(
31                buf,
32                "[{}] {} - {}",
33                format_timestamp(secs),
34                record.level(),
35                record.args()
36            )
37        })
38        .target(env_logger::Target::Pipe(Box::new(log_file)))
39        .init();
40
41    Ok(())
42}
43
44/// Initialize the logger with a custom log file path
45pub fn init_with_path(path: &str) -> Result<(), Box<dyn std::error::Error>> {
46    let log_file = OpenOptions::new().create(true).append(true).open(path)?;
47
48    env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info"))
49        .format(|buf, record| {
50            use std::time::SystemTime;
51
52            let now = SystemTime::now()
53                .duration_since(SystemTime::UNIX_EPOCH)
54                .unwrap();
55            let secs = now.as_secs();
56
57            writeln!(
58                buf,
59                "[{}] {} - {}",
60                format_timestamp(secs),
61                record.level(),
62                record.args()
63            )
64        })
65        .target(env_logger::Target::Pipe(Box::new(log_file)))
66        .init();
67
68    Ok(())
69}
70
71/// Simple timestamp formatter (Unix timestamp to readable format)
72fn format_timestamp(secs: u64) -> String {
73    // Simple ISO-like format without external dependencies
74    // For production use, consider adding chrono crate for better formatting
75    format!("timestamp:{}", secs)
76}