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

Attempt to expand env vars in the path for File and RollingFileAppenders #155

Merged
merged 1 commit into from
Apr 6, 2020
Merged
Show file tree
Hide file tree
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
5 changes: 3 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ json_format = ["serde_json"]
toml_format = ["toml"]

console_appender = ["console_writer", "simple_writer", "pattern_encoder"]
file_appender = ["parking_lot", "simple_writer", "pattern_encoder"]
rolling_file_appender = ["parking_lot", "simple_writer", "pattern_encoder"]
file_appender = ["parking_lot", "simple_writer", "pattern_encoder", "regex"]
rolling_file_appender = ["parking_lot", "simple_writer", "pattern_encoder", "regex"]
compound_policy = []
delete_roller = []
fixed_window_roller = []
Expand Down Expand Up @@ -68,6 +68,7 @@ serde_json = { version = "1.0", optional = true }
serde_yaml = { version = "0.8.4", optional = true }
toml = { version = "0.5", optional = true }
parking_lot = { version = "0.10.0", optional = true }
regex = { version = "1", optional = true }

[target.'cfg(windows)'.dependencies]
winapi = { version = "0.3", optional = true, features = ["handleapi", "minwindef", "processenv", "winbase", "wincon"] }
Expand Down
10 changes: 9 additions & 1 deletion src/append/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,12 @@ impl FileAppenderBuilder {
}

/// Consumes the `FileAppenderBuilder`, producing a `FileAppender`.
/// The path argument can contain environment variables of the form $ENV{name_here},
/// where 'name_here' will be the name of the environment variable that
/// will be resolved. Note that if the variable fails to resolve,
/// $ENV{name_here} will NOT be replaced in the path.
pub fn build<P: AsRef<Path>>(self, path: P) -> io::Result<FileAppender> {
let path = path.as_ref().to_owned();
let path = super::env_util::expand_env_vars(path.as_ref().to_path_buf());
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
Expand Down Expand Up @@ -122,6 +126,10 @@ impl FileAppenderBuilder {
/// kind: file
///
/// # The path of the log file. Required.
/// # The path can contain environment variables of the form $ENV{name_here},
/// # where 'name_here' will be the name of the environment variable that
/// # will be resolved. Note that if the variable fails to resolve,
/// # $ENV{name_here} will NOT be replaced in the path.
/// path: log/foo.log
///
/// # Specifies if the appender should append to or truncate the log file if it
Expand Down
129 changes: 129 additions & 0 deletions src/append/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,20 @@ pub mod file;
#[cfg(feature = "rolling_file_appender")]
pub mod rolling_file;

#[cfg(any(feature = "file_appender", feature = "rolling_file_appender"))]
mod env_util {
pub fn expand_env_vars(path: std::path::PathBuf) -> std::path::PathBuf {
let mut path: String = path.to_string_lossy().into();
let matcher = regex::Regex::new(r#"\$ENV\{([\w][\w|\d|\.|_]*)\}"#).unwrap();
matcher.captures_iter(&path.clone()).for_each(|c| {
if let Ok(s) = std::env::var(&c[1]) {
path = path.replace(&c[0], &s);
}
});
path.into()
}
}

/// A trait implemented by log4rs appenders.
///
/// Appenders take a log record and processes them, for example, by writing it
Expand Down Expand Up @@ -90,3 +104,118 @@ impl<'de> Deserialize<'de> for AppenderConfig {
})
}
}

#[cfg(test)]
mod test {
#[cfg(any(feature = "file_appender", feature = "rolling_file_appender"))]
use std::{
env::{set_var, var},
path::PathBuf,
};

#[test]
#[cfg(any(feature = "file_appender", feature = "rolling_file_appender"))]
fn expand_env_vars_tests() {
set_var("HELLO_WORLD", "GOOD BYE");
#[cfg(target_os = "linux")]
let test_cases = vec![
("$ENV{HOME}", PathBuf::from(var("HOME").unwrap())),
(
"$ENV{HELLO_WORLD}",
PathBuf::from(var("HELLO_WORLD").unwrap()),
),
(
"$ENV{HOME}/test",
PathBuf::from(format!("{}/test", var("HOME").unwrap())),
),
(
"/test/$ENV{HOME}",
PathBuf::from(format!("/test/{}", var("HOME").unwrap())),
),
(
"/test/$ENV{HOME}/test",
PathBuf::from(format!("/test/{}/test", var("HOME").unwrap())),
),
(
"/test$ENV{HOME}/test",
PathBuf::from(format!("/test{}/test", var("HOME").unwrap())),
),
(
"test/$ENV{HOME}/test",
PathBuf::from(format!("test/{}/test", var("HOME").unwrap())),
),
(
"/$ENV{HOME}/test/$ENV{USER}",
PathBuf::from(format!(
"/{}/test/{}",
var("HOME").unwrap(),
var("USER").unwrap()
)),
),
(
"$ENV{SHOULD_NOT_EXIST}",
PathBuf::from("$ENV{SHOULD_NOT_EXIST}"),
),
(
"/$ENV{HOME}/test/$ENV{SHOULD_NOT_EXIST}",
PathBuf::from(format!(
"/{}/test/$ENV{{SHOULD_NOT_EXIST}}",
var("HOME").unwrap()
)),
),
];

#[cfg(target_os = "windows")]
let test_cases = vec![
("$ENV{HOMEPATH}", PathBuf::from(var("HOMEPATH").unwrap())),
(
"$ENV{HELLO_WORLD}",
PathBuf::from(var("HELLO_WORLD").unwrap()),
),
(
"$ENV{HOMEPATH}/test",
PathBuf::from(format!("{}/test", var("HOMEPATH").unwrap())),
),
(
"/test/$ENV{USERNAME}",
PathBuf::from(format!("/test/{}", var("USERNAME").unwrap())),
),
(
"/test/$ENV{USERNAME}/test",
PathBuf::from(format!("/test/{}/test", var("USERNAME").unwrap())),
),
(
"/test$ENV{USERNAME}/test",
PathBuf::from(format!("/test{}/test", var("USERNAME").unwrap())),
),
(
"test/$ENV{USERNAME}/test",
PathBuf::from(format!("test/{}/test", var("USERNAME").unwrap())),
),
(
"$ENV{HOMEPATH}/test/$ENV{USERNAME}",
PathBuf::from(format!(
"{}/test/{}",
var("HOMEPATH").unwrap(),
var("USERNAME").unwrap()
)),
),
(
"$ENV{SHOULD_NOT_EXIST}",
PathBuf::from("$ENV{SHOULD_NOT_EXIST}"),
),
(
"$ENV{HOMEPATH}/test/$ENV{SHOULD_NOT_EXIST}",
PathBuf::from(format!(
"{}/test/$ENV{{SHOULD_NOT_EXIST}}",
var("HOMEPATH").unwrap()
)),
),
];

for (input, expected) in test_cases {
let res = super::env_util::expand_env_vars(input.into());
assert_eq!(res, expected)
}
}
}
11 changes: 10 additions & 1 deletion src/append/rolling_file/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,10 @@ impl RollingFileAppenderBuilder {
}

/// Constructs a `RollingFileAppender`.
/// The path argument can contain environment variables of the form $ENV{name_here},
/// where 'name_here' will be the name of the environment variable that
/// will be resolved. Note that if the variable fails to resolve,
/// $ENV{name_here} will NOT be replaced in the path.
pub fn build<P>(
self,
path: P,
Expand All @@ -258,9 +262,10 @@ impl RollingFileAppenderBuilder {
where
P: AsRef<Path>,
{
let path = super::env_util::expand_env_vars(path.as_ref().to_path_buf());
let appender = RollingFileAppender {
writer: Mutex::new(None),
path: path.as_ref().to_owned(),
path,
append: self.append,
encoder: self
.encoder
Expand All @@ -287,6 +292,10 @@ impl RollingFileAppenderBuilder {
/// kind: rolling_file
///
/// # The path of the log file. Required.
/// # The path can contain environment variables of the form $ENV{name_here},
/// # where 'name_here' will be the name of the environment variable that
/// # will be resolved. Note that if the variable fails to resolve,
/// # $ENV{name_here} will NOT be replaced in the path.
/// path: log/foo.log
///
/// # Specifies if the appender should append to or truncate the log file if it
Expand Down