Skip to content

Commit

Permalink
Add formatters
Browse files Browse the repository at this point in the history
  • Loading branch information
tjardoo committed Sep 11, 2024
1 parent cdc4a3a commit 3cd3e33
Show file tree
Hide file tree
Showing 10 changed files with 133 additions and 51 deletions.
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ Ftail::new()
2024-09-10 14:41:57 TRACE stdout This is a trace message
2024-09-10 14:41:57 DEBUG stdout This is a debug message
2024-09-10 14:41:57 INFO foo bar
2024-09-10 14:41:57 WARN stdout This is a warning
2024-09-10 14:41:57 ERROR stdout This is an error
2024-09-10 14:41:57 WARN stdout This is a warning message
2024-09-10 14:41:57 ERROR stdout This is an error message
```

### Console
Expand Down Expand Up @@ -74,11 +74,11 @@ bar
examples\console\src/main.rs:12
2024-09-10 14:42:21 · WARN
This is a warning
This is a warning message
examples\console\src/main.rs:14
2024-09-10 14:42:21 · ERROR
This is an error
This is an error message
examples\console\src/main.rs:16
```

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

use crate::ansi_escape::TextStyling;
use crate::formatters::{readable::ReadableFormatter, Formatter};

pub struct ConsoleLogger {}

Expand All @@ -10,25 +10,9 @@ impl Log for ConsoleLogger {
}

fn log(&self, record: &log::Record) {
let now = chrono::Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
let formatter = ReadableFormatter::new(record);

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

println!("{} · {}", now.black(), level);
println!("{}", record.args().bold());
println!(
"{}{}{}",
record.file().unwrap().black(),
":".black(),
record.line().unwrap().black()
);
println!();
println!("{}", formatter.format());
}

fn flush(&self) {}
Expand Down
14 changes: 4 additions & 10 deletions src/drivers/daily.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ use std::{
sync::Mutex,
};

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

pub struct DailyLogger {
file: Mutex<LineWriter<File>>,
dir: String,
Expand Down Expand Up @@ -64,18 +66,10 @@ impl Log for DailyLogger {
fn log(&self, record: &log::Record) {
self.rotate_file_if_needed();

let now = chrono::Local::now().format("%Y-%m-%d %H:%M:%S").to_string();

let line = format!(
"{} {} {} {}",
now,
record.level(),
record.target(),
record.args()
);
let formatter = DefaultFormatter::new(record);

let mut file = self.file.lock().unwrap();
writeln!(file, "{}", line).unwrap();
writeln!(file, "{}", formatter.format()).unwrap();
file.flush().unwrap();
}

Expand Down
14 changes: 4 additions & 10 deletions src/drivers/single.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ use std::{
sync::Mutex,
};

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

pub struct SingleLogger {
file: Mutex<LineWriter<File>>,
}
Expand Down Expand Up @@ -36,18 +38,10 @@ impl Log for SingleLogger {
}

fn log(&self, record: &log::Record) {
let now = chrono::Local::now().format("%Y-%m-%d %H:%M:%S").to_string();

let line = format!(
"{} {} {} {}",
now,
record.level(),
record.target(),
record.args()
);
let formatter = DefaultFormatter::new(record);

let mut file = self.file.lock().unwrap();
writeln!(file, "{}", line).unwrap();
writeln!(file, "{}", formatter.format()).unwrap();
file.flush().unwrap();
}

Expand Down
12 changes: 4 additions & 8 deletions src/drivers/stdout.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use log::Log;

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

pub struct StdOutLogger {}

impl Log for StdOutLogger {
Expand All @@ -8,15 +10,9 @@ impl Log for StdOutLogger {
}

fn log(&self, record: &log::Record) {
let now = chrono::Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
let formatter = DefaultFormatter::new(record);

println!(
"{} {} {} {}",
now,
record.level(),
record.target(),
record.args()
);
println!("{}", formatter.format());
}

fn flush(&self) {}
Expand Down
27 changes: 27 additions & 0 deletions src/formatters/default.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
use crate::writer::LogWriter;

use super::Formatter;

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

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

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

format!(
"{} {} {} {}",
writer.get_datetime(),
writer.get_level(self.record),
writer.get_target(self.record),
writer.get_args(self.record),
)
}
}
6 changes: 6 additions & 0 deletions src/formatters/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
pub mod default;
pub mod readable;

pub trait Formatter {
fn format(&self) -> String;
}
46 changes: 46 additions & 0 deletions src/formatters/readable.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
use crate::{ansi_escape::TextStyling, writer::LogWriter};

use super::Formatter;

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

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

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

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(),
};

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

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

if file.is_some() && line.is_some() {
result.push_str(&format!(
"{}{}{}\n",
file.unwrap().black(),
":".black(),
line.unwrap().black()
));
}

result
}
}
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ use log::Log;
mod ansi_escape;
pub mod drivers;
pub mod error;
mod formatters;
mod writer;

pub(crate) struct LogDriver {
driver: Box<dyn Log>,
Expand Down
33 changes: 33 additions & 0 deletions src/writer.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
use log::Record;

pub struct LogWriter {}

impl LogWriter {
pub fn new() -> Self {
Self {}
}

pub fn get_datetime(&self) -> String {
chrono::Local::now().format("%Y-%m-%d %H:%M:%S").to_string()
}

pub fn get_level(&self, record: &Record) -> String {
record.level().to_string()
}

pub fn get_target(&self, record: &Record) -> String {
record.target().to_string()
}

pub fn get_args(&self, record: &Record) -> String {
record.args().to_string()
}

pub fn get_file(&self, record: &Record) -> Option<String> {
record.file().map(|f| f.to_string())
}

pub fn get_line(&self, record: &Record) -> Option<u32> {
record.line()
}
}

0 comments on commit 3cd3e33

Please sign in to comment.