use std::{fs, thread, time::Duration};
use loggit::{
info,
logger::{
add_rotation, init, set_archive_dir, set_compression, set_file, set_log_level,
set_print_to_terminal,
},
Level,
};
const MESSAGES: usize = 50;
#[test]
fn rotation_creates_zip_archive() {
init();
set_print_to_terminal(false).unwrap();
set_log_level(Level::INFO).unwrap();
let ts = chrono::Utc::now().timestamp_nanos();
let prefix = format!("ziprot_{ts}");
let log_pattern = format!("{prefix}_{{date}}_{{time}}.log");
let archive_dir = format!("arch_{ts}");
set_archive_dir(&archive_dir).unwrap();
set_file(&log_pattern).unwrap();
set_compression("zip").unwrap();
add_rotation("1 KB").unwrap();
for n in 0..MESSAGES {
info!("msg {n}: lorem ipsum dolor sit amet, consectetur adipiscing elit.");
}
info!("post-rotation message");
thread::sleep(Duration::from_millis(50));
info!("post-check message");
thread::sleep(Duration::from_millis(50));
let mut zip_found = false;
for entry in fs::read_dir(&archive_dir).expect("cannot read archive dir") {
let path = entry.unwrap().path();
if path.extension().and_then(|s| s.to_str()) == Some("zip") {
zip_found = true;
assert!(
path.metadata().unwrap().len() > 0,
"zip archive is unexpectedly empty"
);
}
}
assert!(zip_found, "no .zip archive produced after rotation");
let mut log_found = false;
for entry in fs::read_dir(".").unwrap() {
let p = entry.unwrap().path();
if p.file_name()
.and_then(|n| n.to_str())
.map(|n| n.starts_with(&prefix) && n.ends_with(".log"))
.unwrap_or(false)
{
log_found = true;
}
}
assert!(log_found, "rotation did not produce a new active log file");
for entry in fs::read_dir(".").unwrap() {
let p = entry.unwrap().path();
if p.file_name()
.and_then(|n| n.to_str())
.map(|n| n.starts_with(&prefix))
.unwrap_or(false)
{
let _ = fs::remove_file(p);
}
}
let _ = fs::remove_dir_all(&archive_dir);
}