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

Support date/time in log file name #374

Open
wants to merge 11 commits into
base: main
Choose a base branch
from
5 changes: 4 additions & 1 deletion docs/Configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,9 @@ my_console_appender:
The _path_ field is required and accepts environment variables of the form
`$ENV{name_here}`. The path can be relative or absolute.

The _path_ field also supports date/time formats such as `$TIME{chrono_format}`. Refer
to [chrono format](https://docs.rs/chrono/latest/chrono/format/strftime/index.html) for date and time formatting syntax

bconn98 marked this conversation as resolved.
Show resolved Hide resolved
The _encoder_ field is optional and can consist of multiple fields. Refer to
the [encoder](#encoder) documention.

Expand All @@ -140,7 +143,7 @@ append to the log file if it exists, false will truncate the existing file.
```yml
my_file_appender:
kind: file
path: $ENV{PWD}/log/test.log
path: $ENV{PWD}/log/test_$TIME{%Y-%m-%d_%H-%M-%S}.log
append: true
```

Expand Down
2 changes: 1 addition & 1 deletion examples/sample_config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ appenders:
level: info
file:
kind: file
path: "log/file.log"
path: "log/file-$TIME{%Y-%m-%d_%H-%M-%S}.log"
encoder:
pattern: "[{d(%Y-%m-%dT%H:%M:%S%.6f)} {h({l}):<5.5} {M}] {m}{n}"
rollingfile:
Expand Down
119 changes: 111 additions & 8 deletions src/append/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
//!
//! Requires the `file_appender` feature.

use chrono::prelude::Local;
use derivative::Derivative;
use log::Record;
use parking_lot::Mutex;
Expand All @@ -11,6 +12,11 @@ use std::{
path::{Path, PathBuf},
};

const TIME_PREFIX: &str = "$TIME{";
const TIME_PREFIX_LEN: usize = TIME_PREFIX.len();
const TIME_SUFFIX: char = '}';
const TIME_SUFFIX_LEN: usize = 1;

#[cfg(feature = "config_parsing")]
use crate::config::{Deserialize, Deserializers};
#[cfg(feature = "config_parsing")]
Expand Down Expand Up @@ -84,31 +90,63 @@ 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.
/// The path argument can contain special patterns that will be resolved:
///
/// - `$ENV{name_here}`: This pattern will be replaced by `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.
/// - `$TIME{chrono_format}`: This pattern will be replaced by `chrono_format`.
/// where 'chrono_format' will be date/time format from chrono crate. Note
/// that if the chrono_format fails to resolve, $TIME{chrono_format} will
/// NOT be replaced in the path.
pub fn build<P: AsRef<Path>>(self, path: P) -> io::Result<FileAppender> {
let path_cow = path.as_ref().to_string_lossy();
let path: PathBuf = expand_env_vars(path_cow).as_ref().into();
if let Some(parent) = path.parent() {
// Expand environment variables in the path
let expanded_env_path: PathBuf = expand_env_vars(path_cow).as_ref().into();
// Apply the date/time format to the path
let final_path = self.date_time_format(expanded_env_path);

if let Some(parent) = final_path.parent() {
fs::create_dir_all(parent)?;
}
let file = OpenOptions::new()
.write(true)
.append(self.append)
.truncate(!self.append)
.create(true)
.open(&path)?;
.open(&final_path)?;

Ok(FileAppender {
path,
path: final_path,
file: Mutex::new(SimpleWriter(BufWriter::with_capacity(1024, file))),
encoder: self
.encoder
.unwrap_or_else(|| Box::<PatternEncoder>::default()),
})
}

fn date_time_format(&self, path: PathBuf) -> PathBuf {
let mut date_time_path = path.to_str().unwrap().to_string();
// Locate the start and end of the placeholder
while let Some(start) = date_time_path.find(TIME_PREFIX) {
if let Some(end) = date_time_path[start..].find(TIME_SUFFIX) {
let end = start + end;
// Extract the date format string
let date_format = &date_time_path[start + TIME_PREFIX_LEN..end];

// Get the current date and time
let now = Local::now();

// Format the current date and time
let formatted_date = now.format(date_format).to_string();

// replacing the placeholder with the formatted date
date_time_path.replace_range(start..end + TIME_SUFFIX_LEN, &formatted_date);
}
}
PathBuf::from(date_time_path)
}
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you add some unit tests for this function? It would be great to just verify some edgecases and verify this is working as intended.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added unit test for this function:

  • valid $TIME{} format
  • invalid $TIME{} format
  • no $TIME{} format
  • multiple $TIME{} in the path

}

/// A deserializer for the `FileAppender`.
Expand Down Expand Up @@ -180,4 +218,69 @@ mod test {
.build(tempdir.path().join("foo.log"))
.unwrap();
}

#[test]
fn test_date_time_format_with_valid_format() {
let current_time = Local::now().format("%Y-%m-%d").to_string();
let tempdir = tempfile::tempdir().unwrap();
let builder = FileAppender::builder()
.build(
tempdir
.path()
.join("foo")
.join("bar")
.join("logs/log-$TIME{%Y-%m-%d}.log"),
)
.unwrap();
let expected_path = tempdir
.path()
.join(format!("foo/bar/logs/log-{}.log", current_time));
assert_eq!(builder.path, expected_path);
}

#[test]
fn test_date_time_format_with_invalid_format() {
let tempdir = tempfile::tempdir().unwrap();
let builder = FileAppender::builder()
.build(
tempdir
.path()
.join("foo")
.join("bar")
.join("logs/log-$TIME{INVALID}.log"),
)
.unwrap();
let expected_path = tempdir.path().join("foo/bar/logs/log-INVALID.log");
assert_eq!(builder.path, expected_path);
}

#[test]
fn test_date_time_format_without_placeholder() {
let tempdir = tempfile::tempdir().unwrap();
let builder = FileAppender::builder()
.build(tempdir.path().join("foo").join("bar").join("bar.log"))
.unwrap();
let expected_path = tempdir.path().join("foo/bar/bar.log");
assert_eq!(builder.path, expected_path);
}

#[test]
fn test_date_time_format_with_multiple_placeholders() {
let current_time = Local::now().format("%Y-%m-%d").to_string();
let tempdir = tempfile::tempdir().unwrap();
let builder = FileAppender::builder()
.build(
tempdir
.path()
.join("foo")
.join("bar")
.join("logs-$TIME{%Y-%m-%d}/log-$TIME{%Y-%m-%d}.log"),
)
.unwrap();
let expected_path = tempdir.path().join(format!(
"foo/bar/logs-{}/log-{}.log",
current_time, current_time
));
assert_eq!(builder.path, expected_path);
}
}
Loading