Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add possibility to compress log files with Zstandard #363

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ all_components = [
]

gzip = ["flate2"]
zstandard = ["zstd"]
bconn98 marked this conversation as resolved.
Show resolved Hide resolved

[[bench]]
name = "rotation"
Expand All @@ -58,6 +59,7 @@ harness = false
arc-swap = "1.6"
chrono = { version = "0.4.23", optional = true, features = ["clock"], default-features = false }
flate2 = { version = "1.0", optional = true }
zstd = { version = "0.13", optional = true }
fnv = "1.0"
humantime = { version = "2.1", optional = true }
log = { version = "0.4.20", features = ["std"] }
Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,11 +73,12 @@ substantial performance issue with the `gzip` feature. When rolling files
it will zip log archives automatically. This is a problem when the log archives
bconn98 marked this conversation as resolved.
Show resolved Hide resolved
are large as the zip happens in the main thread and will halt the process while
the zip is completed.
You might face the same issue also with the `zstandard` feature.
bconn98 marked this conversation as resolved.
Show resolved Hide resolved

The methods to mitigate this are as follows.

1. Use the `background_rotation` feature which spawns an os thread to do the compression.
2. Do not enable the `gzip` feature.
2. Do not enable neither the `gzip` nor the `zstandard` feature.
bconn98 marked this conversation as resolved.
Show resolved Hide resolved
3. Ensure the archives are small enough that the compression time is acceptable.

For more information see the PR that added [`background_rotation`](https://github.com/estk/log4rs/pull/117).
Expand Down
13 changes: 9 additions & 4 deletions benches/rotation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,15 @@ fn mk_config(file_size: u64, file_count: u32) -> log4rs::config::Config {
let log_path = LOGDIR.path();
let log_pattern = log_path.join("log.log");

#[cfg(feature = "gzip")]
let roll_pattern = format!("{}/{}", log_path.to_string_lossy(), "log.{}.gz");
#[cfg(not(feature = "gzip"))]
let roll_pattern = format!("{}/{}", log_path.to_string_lossy(), "log.{}");
let roll_pattern = {
if cfg!(feature = "gzip") {
format!("{}/{}", log_path.to_string_lossy(), "log.{}.gz")
} else if cfg!(feature = "zstandard") {
format!("{}/{}", log_path.to_string_lossy(), "log.{}.zst")
} else {
format!("{}/{}", log_path.to_string_lossy(), "log.{}")
}
};

use log::LevelFilter;
use log4rs::{
Expand Down
3 changes: 3 additions & 0 deletions docs/Configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,9 @@ double curly brace `{}`. For example `archive/foo.{}.log`. Each instance of
`{}` will be replaced with the index number of the configuration file. Note
that if the file extension of the pattern is `.gz` and the `gzip` Cargo
feature is enabled, the archive files will be gzip-compressed.
If the file extension of the pattern is `.zst` and the `zstandard` Cargo
feature is enabled, the archive files will be compressed the
bconn98 marked this conversation as resolved.
Show resolved Hide resolved
[Zstandard](https://facebook.github.io/zstd/) compression algorithm.

> Note: This pattern field is only used for archived files. The `path` field
> of the higher level `rolling_file` will be used for the active log file.
Expand Down
74 changes: 73 additions & 1 deletion src/append/rolling_file/policy/compound/roll/fixed_window.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ enum Compression {
None,
#[cfg(feature = "gzip")]
Gzip,
#[cfg(feature = "zstandard")]
Zstd,
}

impl Compression {
Expand All @@ -52,6 +54,19 @@ impl Compression {
drop(o.finish()?);
drop(i); // needs to happen before remove_file call on Windows

fs::remove_file(src)
},
#[cfg(feature = "zstandard")]
Compression::Zstd => {
use std::fs::File;
let mut i = File::open(src)?;
let mut o = {
let target = File::create(dst)?;
zstd::Encoder::new(target, zstd::DEFAULT_COMPRESSION_LEVEL)?
};
io::copy(&mut i, &mut o)?;
drop(o.finish()?);
drop(i);
fs::remove_file(src)
}
}
Expand Down Expand Up @@ -274,7 +289,13 @@ impl FixedWindowRollerBuilder {
#[cfg(not(feature = "gzip"))]
Some(e) if e == "gz" => {
bail!("gzip compression requires the `gzip` feature");
}
},
#[cfg(feature = "zstandard")]
Some(e) if e == "zst" => Compression::Zstd,
#[cfg(not(feature = "zstandard"))]
Some(e) if e == "zst" => {
bail!("zstd compression requires the `zstandard` feature");
},
_ => Compression::None,
};

Expand Down Expand Up @@ -560,6 +581,57 @@ mod test {
assert_eq!(contents, actual);
}

#[test]
#[cfg_attr(feature = "zstandard", ignore)]
fn unsupported_zstd() {
let dir = tempfile::tempdir().unwrap();

let pattern = dir.path().join("{}.zst");
let roller = FixedWindowRoller::builder()
.build(pattern.to_str().unwrap(), 2);
assert!(roller.is_err());
assert!(roller
.unwrap_err()
.to_string()
.contains("zstd compression requires the `zstandard` feature"));
}

#[test]
#[cfg_attr(not(feature = "zstandard"), ignore)]
// or should we force windows user to install zstd
#[cfg(not(windows))]
fn supported_zstd() {
use std::process::Command;

let dir = tempfile::tempdir().unwrap();

let pattern = dir.path().join("{}.zst");
let roller = FixedWindowRoller::builder()
.build(pattern.to_str().unwrap(), 2)
.unwrap();

let contents = (0..10000).map(|i| i as u8).collect::<Vec<_>>();

let file = dir.path().join("foo.log");
File::create(&file).unwrap().write_all(&contents).unwrap();

roller.roll(&file).unwrap();
wait_for_roller(&roller);

assert!(Command::new("zstd")
.arg("-d")
.arg(dir.path().join("0.zst"))
.status()
.unwrap()
.success());

let mut file = File::open(dir.path().join("0")).unwrap();
let mut actual = vec![];
file.read_to_end(&mut actual).unwrap();

assert_eq!(contents, actual);
}

#[test]
fn roll_with_env_var() {
std::env::set_var("LOG_DIR", "test_log_dir");
Expand Down