Skip to content

Commit

Permalink
Add Config support
Browse files Browse the repository at this point in the history
  • Loading branch information
tjardoo committed Sep 12, 2024
1 parent 0def8b6 commit aa4ba76
Show file tree
Hide file tree
Showing 13 changed files with 171 additions and 57 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ keywords = ["log", "logging"]
[dependencies]
log = { version = "0.4", features = ["std"] }
chrono = "0.4"
chrono-tz = "0.10"

[workspace]
members = [
Expand Down
16 changes: 13 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,30 @@ Ftail is simple logging implementation for the `log` crate with support for mult

## Usage

Add the following dependencies to your `Cargo.toml` file:

```toml
[dependencies]
log = "0.4"
ftail = "0.1"
```

Add the following code to your `main.rs` or `lib.rs` file:

```rust
use ftail::Ftail;
use log::LevelFilter;

Ftail::new()
.timezone(chrono_tz::Europe::Amsterdam) // optional (default is UTC)
.console(LevelFilter::Debug)
.daily_file("logs", LevelFilter::Error)
.init()?;

// log messages anywhere in your code
log::trace!("This is a trace message");
log::debug!("This is a debug message");
log::info!("This is an info message");
log::info!(target: "foo", "bar");
log::warn!("This is a warning message");
log::error!("This is an error message");
```
Expand Down Expand Up @@ -121,8 +133,6 @@ Ftail::new()

Create your own log driver.

You can add text formatting, by using the `use ftail::ansi_escape::TextStyling;` module.

```rust
Ftail::new()
.custom(Box::new(Box::new(CustomLogger {})), LevelFilter::Debug)
Expand Down
1 change: 1 addition & 0 deletions examples/console/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ publish = false
[dependencies]
log = "0.4"
ftail = { path = "../../../ftail" }
chrono-tz = "0.10"
7 changes: 6 additions & 1 deletion examples/console/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@ use log::LevelFilter;
// This example demonstrates how to log messages to stdout.

fn main() -> Result<(), Box<dyn std::error::Error>> {
Ftail::new().console(LevelFilter::Off).init()?;
Ftail::new()
.timezone(chrono_tz::UTC)
// .timezone(chrono_tz::Europe::Amsterdam)
.datetime_format("%d-%m-%Y %H:%M:%S")
.console(LevelFilter::Off)
.init()?;

log::trace!("This is a trace message");

Expand Down
16 changes: 13 additions & 3 deletions src/drivers/console.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,27 @@
use log::Log;

use crate::formatters::{default::DefaultFormatter, Formatter};
use crate::formatters::{default::DefaultFormatter, Config, Formatter};

/// A logger that logs messages to the console.
pub struct ConsoleLogger {}
pub struct ConsoleLogger {
config: Config,
}

impl ConsoleLogger {
pub fn new(config: Config) -> Self {
ConsoleLogger { config }
}
}

impl Log for ConsoleLogger {
fn enabled(&self, _metadata: &log::Metadata) -> bool {
true
}

fn log(&self, record: &log::Record) {
let formatter = DefaultFormatter::new(record);
let config = self.config.clone();

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

println!("{}", formatter.format());
}
Expand Down
10 changes: 7 additions & 3 deletions src/drivers/daily_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,19 @@ use std::{

use crate::{
error::FtailError,
formatters::{default::DefaultFormatter, Formatter},
formatters::{default::DefaultFormatter, Config, Formatter},
};

/// A logger that logs messages to a daily log file.
pub struct DailyFileLogger {
file: Mutex<LineWriter<File>>,
dir: String,
current_date: Mutex<String>,
config: Config,
}

impl DailyFileLogger {
pub fn new(dir: &str) -> Result<Self, FtailError> {
pub fn new(dir: &str, config: Config) -> Result<Self, FtailError> {
let today = chrono::Local::now().format("%Y-%m-%d").to_string();
let path = format!("{}/{}.log", dir, today);

Expand All @@ -38,6 +39,7 @@ impl DailyFileLogger {
file: Mutex::new(LineWriter::new(file)),
dir: dir.to_string(),
current_date: Mutex::new(today),
config,
})
}

Expand Down Expand Up @@ -70,7 +72,9 @@ impl Log for DailyFileLogger {
fn log(&self, record: &log::Record) {
self.rotate_file_if_needed();

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

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

let mut file = self.file.lock().unwrap();
writeln!(file, "{}", formatter.format()).unwrap();
Expand Down
16 changes: 13 additions & 3 deletions src/drivers/formatted_console.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,27 @@
use log::Log;

use crate::formatters::{readable::ReadableFormatter, Formatter};
use crate::formatters::{readable::ReadableFormatter, Config, Formatter};

/// A logger that logs formatted messages to the console.
pub struct FormattedConsoleLogger {}
pub struct FormattedConsoleLogger {
config: Config,
}

impl FormattedConsoleLogger {
pub fn new(config: Config) -> Self {
FormattedConsoleLogger { config }
}
}

impl Log for FormattedConsoleLogger {
fn enabled(&self, _metadata: &log::Metadata) -> bool {
true
}

fn log(&self, record: &log::Record) {
let formatter = ReadableFormatter::new(record);
let config = self.config.clone();

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

println!("{}", formatter.format());
}
Expand Down
9 changes: 6 additions & 3 deletions src/drivers/single_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,17 @@ use std::{

use crate::{
error::FtailError,
formatters::{default::DefaultFormatter, Formatter},
formatters::{default::DefaultFormatter, Config, Formatter},
};

/// A logger that logs messages to a single log file.
pub struct SingleFileLogger {
file: Mutex<LineWriter<File>>,
config: Config,
}

impl SingleFileLogger {
pub fn new(path: &str, append: bool) -> Result<Self, FtailError> {
pub fn new(path: &str, append: bool, config: Config) -> Result<Self, FtailError> {
let file = std::fs::OpenOptions::new()
.create(true)
.write(true)
Expand All @@ -32,6 +33,7 @@ impl SingleFileLogger {

Ok(SingleFileLogger {
file: Mutex::new(LineWriter::new(file)),
config,
})
}
}
Expand All @@ -42,7 +44,8 @@ impl Log for SingleFileLogger {
}

fn log(&self, record: &log::Record) {
let formatter = DefaultFormatter::new(record);
let config = self.config.clone();
let formatter = DefaultFormatter::new(record, config);

let mut file = self.file.lock().unwrap();
writeln!(file, "{}", formatter.format()).unwrap();
Expand Down
17 changes: 10 additions & 7 deletions src/formatters/default.rs
Original file line number Diff line number Diff line change
@@ -1,27 +1,30 @@
use crate::writer::LogWriter;
use crate::{formatters::Config, writer::LogWriter};

use super::Formatter;

pub struct DefaultFormatter<'a> {
record: &'a log::Record<'a>,
config: Config,
}

impl DefaultFormatter<'_> {
pub fn new<'a>(record: &'a log::Record<'a>) -> DefaultFormatter<'a> {
DefaultFormatter { record }
pub fn new<'a>(record: &'a log::Record<'a>, config: Config) -> DefaultFormatter<'a> {
DefaultFormatter { record, config }
}
}

impl<'a> Formatter for DefaultFormatter<'a> {
fn format(&self) -> String {
let writer = LogWriter::new();
let config = self.config.clone();

let writer = LogWriter::new(self.record, config);

format!(
"{} {} {} {}",
writer.get_datetime(),
writer.get_level(self.record),
writer.get_target(self.record),
writer.get_args(self.record),
writer.get_level(),
writer.get_target(),
writer.get_args(),
)
}
}
21 changes: 21 additions & 0 deletions src/formatters/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,24 @@ pub mod readable;
pub trait Formatter {
fn format(&self) -> String;
}

#[derive(Clone)]
pub struct Config {
pub datetime_format: String,
pub timezone: chrono_tz::Tz,
}

impl Config {
pub fn new() -> Config {
Config {
datetime_format: "%Y-%m-%d %H:%M:%S".to_string(),
timezone: chrono_tz::Tz::UTC,
}
}
}

impl Default for Config {
fn default() -> Self {
Self::new()
}
}
27 changes: 15 additions & 12 deletions src/formatters/readable.rs
Original file line number Diff line number Diff line change
@@ -1,36 +1,39 @@
use crate::{ansi_escape::TextStyling, writer::LogWriter};

use super::Formatter;
use super::{Config, Formatter};

pub struct ReadableFormatter<'a> {
record: &'a log::Record<'a>,
config: Config,
}

impl ReadableFormatter<'_> {
pub fn new<'a>(record: &'a log::Record<'a>) -> ReadableFormatter<'a> {
ReadableFormatter { record }
pub fn new<'a>(record: &'a log::Record<'a>, config: Config) -> ReadableFormatter<'a> {
ReadableFormatter { record, config }
}
}

impl<'a> Formatter for ReadableFormatter<'a> {
fn format(&self) -> String {
let writer = LogWriter::new();
let config = self.config.clone();

let writer = LogWriter::new(self.record, config);

let mut result = String::new();

let level = match self.record.level() {
log::Level::Trace => writer.get_level(self.record).bold().black(),
log::Level::Debug => writer.get_level(self.record).bold().blue(),
log::Level::Info => writer.get_level(self.record).bold().green(),
log::Level::Warn => writer.get_level(self.record).bold().yellow(),
log::Level::Error => writer.get_level(self.record).bold().red(),
log::Level::Trace => writer.get_level().bold().black(),
log::Level::Debug => writer.get_level().bold().blue(),
log::Level::Info => writer.get_level().bold().green(),
log::Level::Warn => writer.get_level().bold().yellow(),
log::Level::Error => writer.get_level().bold().red(),
};

result.push_str(&format!("{} · {}\n", writer.get_datetime().black(), level));
result.push_str(&format!("{}\n", writer.get_args(self.record).bold()));
result.push_str(&format!("{}\n", writer.get_args().bold()));

let file = writer.get_file(self.record);
let line = writer.get_line(self.record);
let file = writer.get_file();
let line = writer.get_line();

if file.is_some() && line.is_some() {
result.push_str(&format!(
Expand Down
Loading

0 comments on commit aa4ba76

Please sign in to comment.