Skip to content

Commit

Permalink
WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
tjardoo committed Sep 12, 2024
1 parent 3cd3e33 commit f38bd10
Show file tree
Hide file tree
Showing 21 changed files with 147 additions and 65 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Changelog

## v0.1.0 (2024-09-12)

- Initial release
6 changes: 3 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ chrono = "0.4"
[workspace]
members = [
"examples/console",
"examples/custom",
"examples/daily",
"examples/formatted_console",
"examples/single",
"examples/daily",
"examples/stack",
"examples/stdout",
"examples/custom",
]
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 Tjardo

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
16 changes: 9 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

Ftail is simple logging implementation for the `log` crate with support for multiple drivers.

- [Stdout (standard output logging)](#stdout)
- [Console (formatted output logging)](#console)
- [Console (standard output logging)](#console)
- [Formatted console (formatted output logging)](#formatted-console)
- [Single (single log file)](#single)
- [Daily (daily log rotation)](#daily)
- [Custom (custom log driver)](#custom)
Expand All @@ -24,17 +24,17 @@ log::info!("This is an info message");

## Drivers

### Stdout
### Console

Logs to the standard output.
Logs to the standard output without any formatting.

The `stdout` driver takes the following parameters:

- `level`: the minumum log level to log

```rust
Ftail::new()
.stdout(LevelFilter::Trace)
.console(LevelFilter::Trace)
.init()?;
```

Expand All @@ -46,7 +46,7 @@ Ftail::new()
2024-09-10 14:41:57 ERROR stdout This is an error message
```

### Console
### Formatted Console

Logs to the standard output with formatted and colored output.

Expand All @@ -56,7 +56,7 @@ The `console` driver takes the following parameters:

```rust
Ftail::new()
.console(LevelFilter::Trace)
.formatted_console(LevelFilter::Trace)
.init()?;
```

Expand Down Expand Up @@ -117,6 +117,8 @@ 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
4 changes: 3 additions & 1 deletion examples/console/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
use ftail::Ftail;
use log::LevelFilter;

// This example demonstrates how to log messages to stdout.

fn main() -> Result<(), Box<dyn std::error::Error>> {
Ftail::new().console(LevelFilter::Trace).init()?;
Ftail::new().console(LevelFilter::Off).init()?;

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

Expand Down
14 changes: 12 additions & 2 deletions examples/custom/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use ftail::Ftail;
use ftail::{ansi_escape::TextStyling, Ftail};
use log::{LevelFilter, Log};

// This example demonstrates how to log messages to stdout with custom styling.

fn main() -> Result<(), Box<dyn std::error::Error>> {
Ftail::new()
.custom(Box::new(Box::new(CustomLogger {})), LevelFilter::Debug)
Expand Down Expand Up @@ -29,7 +31,15 @@ impl Log for CustomLogger {
fn log(&self, record: &log::Record) {
let time = chrono::Local::now().format("%H:%M:%S").to_string();

println!("{} {} {}", time, record.level(), record.args());
let level = match record.level() {
log::Level::Trace => record.level().black().to_string(),
log::Level::Debug => record.level().blue().to_string(),
log::Level::Info => record.level().green().to_string(),
log::Level::Warn => record.level().yellow().to_string(),
log::Level::Error => record.level().red().to_string(),
};

println!("{} [{}] {}", time.black(), level.bold(), record.args());
}

fn flush(&self) {}
Expand Down
2 changes: 2 additions & 0 deletions examples/daily/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use ftail::Ftail;
use log::LevelFilter;

// This example demonstrates how to log messages to a daily log file in the logs directory.

fn main() -> Result<(), Box<dyn std::error::Error>> {
Ftail::new().daily("logs", LevelFilter::Trace).init()?;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[package]
name = "stdout"
name = "formatted_console"
version = "0.1.0"
edition = "2021"
publish = false
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
use ftail::Ftail;
use log::LevelFilter;

// This example demonstrates how to log formatted messages to the console.

fn main() -> Result<(), Box<dyn std::error::Error>> {
Ftail::new().stdout(LevelFilter::Trace).init()?;
Ftail::new().formatted_console(LevelFilter::Trace).init()?;

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

Expand Down
2 changes: 2 additions & 0 deletions examples/single/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use ftail::Ftail;
use log::LevelFilter;

// This example demonstrates how to log messages to a single file in the logs directory.

fn main() -> Result<(), Box<dyn std::error::Error>> {
Ftail::new()
.single("logs/demo.log", true, LevelFilter::Trace)
Expand Down
1 change: 1 addition & 0 deletions examples/stack/logs/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
*.log
7 changes: 5 additions & 2 deletions examples/stack/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
use ftail::Ftail;
use log::LevelFilter;

// This example demonstrates how to log messages to different files based on their log level.

fn main() -> Result<(), Box<dyn std::error::Error>> {
Ftail::new()
.stdout(LevelFilter::Trace)
.console(LevelFilter::Trace)
.single("logs/trace.log", true, LevelFilter::Trace)
.single("logs/error.log", true, LevelFilter::Error)
.init()?;

log::trace!("This is a trace message");
Expand All @@ -15,6 +17,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {

log::warn!("This is a warning message");

// the `error.log` will only contain this message
log::error!("This is an error message");

Ok(())
Expand Down
5 changes: 3 additions & 2 deletions src/drivers/console.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use log::Log;

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

/// A logger that logs messages to the console.
pub struct ConsoleLogger {}

impl Log for ConsoleLogger {
Expand All @@ -10,7 +11,7 @@ impl Log for ConsoleLogger {
}

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

println!("{}", formatter.format());
}
Expand Down
18 changes: 11 additions & 7 deletions src/drivers/daily.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,36 +5,40 @@ use std::{
sync::Mutex,
};

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

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

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

let file = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(path)
.unwrap();
.map_err(FtailError::IoError)?;

let md = std::fs::metadata(dir).unwrap();
let md = std::fs::metadata(dir).map_err(FtailError::IoError)?;

if md.permissions().readonly() {
panic!("The logs directory `{dir}` is readonly");
return Err(FtailError::PermissionsError(dir.to_string()));
}

DailyLogger {
Ok(DailyLogger {
file: Mutex::new(LineWriter::new(file)),
dir: dir.to_string(),
current_date: Mutex::new(today),
}
})
}

fn rotate_file_if_needed(&self) {
Expand Down
20 changes: 20 additions & 0 deletions src/drivers/formatted_console.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
use log::Log;

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

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

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

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

println!("{}", formatter.format());
}

fn flush(&self) {}
}
2 changes: 1 addition & 1 deletion src/drivers/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
pub mod console;
pub mod daily;
pub mod formatted_console;
pub mod single;
pub mod stdout;
18 changes: 11 additions & 7 deletions src/drivers/single.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,30 +5,34 @@ use std::{
sync::Mutex,
};

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

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

impl SingleLogger {
pub fn new(path: &str, append: bool) -> Self {
pub fn new(path: &str, append: bool) -> Result<Self, FtailError> {
let file = std::fs::OpenOptions::new()
.create(true)
.write(true)
.append(append)
.open(path)
.unwrap();
.map_err(FtailError::IoError)?;

let md = std::fs::metadata(path).unwrap();
let md = std::fs::metadata(path).map_err(FtailError::IoError)?;

if md.permissions().readonly() {
panic!("The logs directory `{path}` is readonly");
return Err(FtailError::PermissionsError(path.to_string()));
}

SingleLogger {
Ok(SingleLogger {
file: Mutex::new(LineWriter::new(file)),
}
})
}
}

Expand Down
19 changes: 0 additions & 19 deletions src/drivers/stdout.rs

This file was deleted.

10 changes: 8 additions & 2 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ use log::SetLoggerError;
#[derive(Debug)]
pub enum FtailError {
SetLoggerError(SetLoggerError),
DuplicatedDriver(String),
NoDriversError,
IoError(std::io::Error),
PermissionsError(String),
}

impl std::error::Error for FtailError {}
Expand All @@ -14,7 +16,11 @@ impl Display for FtailError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
FtailError::SetLoggerError(e) => write!(f, "Error setting logger: {}", e),
FtailError::DuplicatedDriver(driver) => write!(f, "Duplicated driver: {}", driver),
FtailError::NoDriversError => write!(f, "No drivers were added to the logger"),
FtailError::IoError(e) => write!(f, "I/O error: {}", e),
FtailError::PermissionsError(path) => {
write!(f, "The path {} is read-only", path)
}
}
}
}
Loading

0 comments on commit f38bd10

Please sign in to comment.