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 level filters #4

Merged
merged 4 commits into from
Sep 17, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
WIP
  • Loading branch information
tjardoo committed Sep 17, 2024
commit 8821b3d091f3aa6bc328ee755d217bfb7788e494
3 changes: 0 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,6 @@ timezone = ["chrono-tz"]
[dev-dependencies]
ftail = { path = ".", features = ["timezone"] }

[profile.test]
features = ["timezone"]

[workspace]
members = [
"examples/console",
Expand Down
2 changes: 1 addition & 1 deletion examples/console/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
// Level::Warn,
Level::Error,
]) // optional
.filter_targets(vec!["foo"]) // optional
.filter_targets(vec!["foo".to_string()]) // optional
.init()?;

log::trace!("This is a trace message");
Expand Down
14 changes: 11 additions & 3 deletions src/drivers/console.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use log::Log;
use log::{LevelFilter, Log};

use crate::{
formatters::{default::DefaultFormatter, Formatter},
Expand All @@ -17,11 +17,19 @@ impl ConsoleLogger {
}

impl Log for ConsoleLogger {
fn enabled(&self, _metadata: &log::Metadata) -> bool {
true
fn enabled(&self, metadata: &log::Metadata) -> bool {
if self.config.level_filter == LevelFilter::Off {
return true;
}

metadata.level() <= self.config.level_filter
}

fn log(&self, record: &log::Record) {
if !self.enabled(record.metadata()) {
return;
}

let formatter = DefaultFormatter::new(record, &self.config);

println!("{}", formatter.format());
Expand Down
14 changes: 11 additions & 3 deletions src/drivers/daily_file.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use log::Log;
use log::{LevelFilter, Log};
use std::{
fs::File,
io::{LineWriter, Write},
Expand Down Expand Up @@ -70,11 +70,19 @@ impl DailyFileLogger {
}

impl Log for DailyFileLogger {
fn enabled(&self, _metadata: &log::Metadata) -> bool {
true
fn enabled(&self, metadata: &log::Metadata) -> bool {
if self.config.level_filter == LevelFilter::Off {
return true;
}

metadata.level() <= self.config.level_filter
}

fn log(&self, record: &log::Record) {
if !self.enabled(record.metadata()) {
return;
}

rotate_if_exceeds_max_file_size(&self.file, self.file_path.clone(), &self.config);
self.rotate_daily_file();

Expand Down
14 changes: 11 additions & 3 deletions src/drivers/formatted_console.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use log::Log;
use log::{LevelFilter, Log};

use crate::{
formatters::{readable::ReadableFormatter, Formatter},
Expand All @@ -17,11 +17,19 @@ impl FormattedConsoleLogger {
}

impl Log for FormattedConsoleLogger {
fn enabled(&self, _metadata: &log::Metadata) -> bool {
true
fn enabled(&self, metadata: &log::Metadata) -> bool {
if self.config.level_filter == LevelFilter::Off {
return true;
}

metadata.level() <= self.config.level_filter
}

fn log(&self, record: &log::Record) {
if !self.enabled(record.metadata()) {
return;
}

let formatter = ReadableFormatter::new(record, &self.config);

println!("{}", formatter.format());
Expand Down
2 changes: 1 addition & 1 deletion src/drivers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@ pub mod daily_file;
pub mod formatted_console;
pub mod single_file;
#[cfg(test)]
mod test;
pub mod test;
14 changes: 11 additions & 3 deletions src/drivers/single_file.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use log::Log;
use log::{LevelFilter, Log};
use std::{
fs::File,
io::{LineWriter, Write},
Expand Down Expand Up @@ -44,11 +44,19 @@ impl SingleFileLogger {
}

impl Log for SingleFileLogger {
fn enabled(&self, _metadata: &log::Metadata) -> bool {
true
fn enabled(&self, metadata: &log::Metadata) -> bool {
if self.config.level_filter == LevelFilter::Off {
return true;
}

metadata.level() <= self.config.level_filter
}

fn log(&self, record: &log::Record) {
if !self.enabled(record.metadata()) {
return;
}

rotate_if_exceeds_max_file_size(&self.file, self.file_path.clone(), &self.config);

let formatter = DefaultFormatter::new(record, &self.config);
Expand Down
138 changes: 17 additions & 121 deletions src/drivers/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,147 +2,43 @@ use crate::{
formatters::{default::DefaultFormatter, Formatter},
Config,
};
use log::Log;
use std::{io::Write, sync::Mutex};
use log::{LevelFilter, Log};
use std::sync::{Arc, Mutex};

struct TestLogger {
buffer: Mutex<Vec<u8>>,
config: Config,
pub struct TestLogger {
pub buffer: Arc<Mutex<Vec<String>>>,
pub config: Config,
}

impl TestLogger {
#[cfg(test)]
pub fn new(config: Config) -> Self {
TestLogger {
buffer: Mutex::new(vec![]),
buffer: Arc::new(Mutex::new(Vec::new())),
config,
}
}
}

impl Log for TestLogger {
fn enabled(&self, _metadata: &log::Metadata) -> bool {
true
fn enabled(&self, metadata: &log::Metadata) -> bool {
if self.config.level_filter == LevelFilter::Off {
return true;
}

metadata.level() <= self.config.level_filter
}

fn log(&self, record: &log::Record) {
let mut buffer = self.buffer.lock().unwrap();
if !self.enabled(record.metadata()) {
return;
}

let formatter = DefaultFormatter::new(record, &self.config);

buffer.write_all(formatter.format().as_bytes()).unwrap();
let mut buffer = self.buffer.lock().unwrap();
buffer.push(formatter.format());
}

fn flush(&self) {}
}

fn remove_datetime_from_message(message: String, config: Config) -> String {
#[cfg(feature = "timezone")]
let datetime = chrono::Local::now()
.with_timezone(&config.timezone)
.format(&config.datetime_format)
.to_string();

#[cfg(not(feature = "timezone"))]
let datetime = chrono::Local::now()
.format(&config.datetime_format)
.to_string();

let len = datetime.len() + 1; // +1 for the space after the datetime

message[len..].to_string()
}

#[cfg(test)]
mod tests {
use log::{Level, Log, Metadata, Record};

use crate::{
drivers::test::{remove_datetime_from_message, TestLogger},
Config,
};

fn get_message_from_logger(config: Config, record: Record, is_remove_datetime: bool) -> String {
let logger = TestLogger::new(config.clone());

logger.log(&record);

let buffer = logger.buffer.lock().unwrap();
let message = std::str::from_utf8(&buffer).unwrap().to_string();

if !is_remove_datetime {
return message;
}

remove_datetime_from_message(message, config)
}

#[test]
fn test_log_message() {
let config = Config::default();

let record = Record::builder()
.metadata(
Metadata::builder()
.level(Level::Info)
.target("test")
.build(),
)
.args(format_args!("Hello, world!"))
.build();

assert_eq!(
get_message_from_logger(config, record, true),
"INFO test Hello, world!"
);
}

#[test]
fn test_log_message_with_custom_datetime_format() {
let config = Config {
datetime_format: "%Y-%m-%d %H:%M:%S%.3f".to_string(),
..Default::default()
};

let record = Record::builder()
.metadata(
Metadata::builder()
.level(Level::Error)
.target("foo")
.build(),
)
.args(format_args!("bar"))
.build();

assert_eq!(
get_message_from_logger(config, record, true),
"ERROR foo bar"
);
}

#[test]
#[cfg(feature = "timezone")]
fn test_log_message_with_specified_timezone() {
let config = Config {
datetime_format: "%Z".to_string(),
#[cfg(feature = "timezone")]
timezone: ftail::Tz::Australia__Sydney,
..Default::default()
};

let record = Record::builder()
.metadata(
Metadata::builder()
.level(Level::Debug)
.target("test")
.build(),
)
.args(format_args!("Hello, world!"))
.build();

assert_eq!(
get_message_from_logger(config, record, false),
"AEST DEBUG test Hello, world!"
);
}
}
7 changes: 5 additions & 2 deletions src/formatters/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use log::LevelFilter;

use crate::Config;

pub mod default;
Expand All @@ -10,12 +12,13 @@ pub trait Formatter {
impl Config {
pub fn new() -> Config {
Config {
level_filter: LevelFilter::Off,
datetime_format: "%Y-%m-%d %H:%M:%S".to_string(),
#[cfg(feature = "timezone")]
timezone: chrono_tz::Tz::UTC,
max_file_size: None,
level_filters: None,
target_filters: None,
levels: None,
targets: None,
}
}
}
Expand Down
Loading
Loading