Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,8 @@ pub enum RotationMode {
Bytes(usize),
/// Cut the log file at line breaks.
Lines(usize),
/// Cut the log file after surpassing size in bytes (but having written a complete buffer from a write call.)
BytesSurpassed(usize),
}

/// The main writer used for rotating logs.
Expand Down Expand Up @@ -175,6 +177,9 @@ impl FileRotate {
RotationMode::Lines(lines) => {
assert!(lines > 0);
}
RotationMode::BytesSurpassed(bytes) => {
assert!(bytes > 0);
}
};

Self {
Expand Down Expand Up @@ -246,6 +251,15 @@ impl Write for FileRotate {
return Err(err);
}
}
RotationMode::BytesSurpassed(bytes) => {
if let Some(Err(err)) = self.file.as_mut().map(|file| file.write(&buf)) {
return Err(err);
}
self.count += buf.len();
if self.count > bytes {
self.rotate()?
}
}
}
Ok(written)
}
Expand Down Expand Up @@ -307,6 +321,31 @@ mod tests {
assert_eq!("d\n", fs::read_to_string("target/rotate/log.0").unwrap());
}

#[test]
fn write_complete_record_until_bytes_surpassed() {
let _ = fs::remove_dir_all("target/surpassed_bytes");
fs::create_dir("target/surpassed_bytes").unwrap();

let mut rot = FileRotate::new(
"target/surpassed_bytes/log",
RotationMode::BytesSurpassed(1),
1,
);

write!(rot, "0123456789").unwrap();
rot.flush().unwrap();
assert!(Path::new("target/surpassed_bytes/log.0").exists());
// shouldn't exist yet - because entire record was written in one shot
assert!(!Path::new("target/surpassed_bytes/log.1").exists());

// This should create the second file
write!(rot, "0123456789").unwrap();
rot.flush().unwrap();
assert!(Path::new("target/surpassed_bytes/log.1").exists());

fs::remove_dir_all("target/surpassed_bytes").unwrap();
}

#[quickcheck_macros::quickcheck]
fn arbitrary_lines(count: usize) {
let _ = fs::remove_dir_all("target/arbitrary_lines");
Expand Down