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

feature gate tokio dependency #1

Merged
merged 1 commit into from
Aug 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
# Changelog

## 0.1.3 - 2024-08-02

### New features
- Feature gate tokio dependency

## 0.1.2 - 2024-07-08

## 0.1.1 - 2024-05-17

### New features
Expand Down
10 changes: 7 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
[package]
name = "speak-easy"
version = "0.1.2"
version = "0.1.3"
authors = ["stefanodecillis"]
edition = "2021"
description = "Logging functionalities with different levels and rotation options built on top of tokio-rs tracing."
description = "Logging functionalities with different levels and rotation options built on top of tracing and compatible with of tokio-rs."
license = "MIT"
readme = "README.md"
repository = "https://github.com/stefanodecillis/speak-easy"
Expand All @@ -15,9 +15,13 @@ categories = [
]
keywords = ["logging", "tracing", "async"]

[features]
default = ["tokio_async"]
tokio_async = ["tokio"]


[dependencies]
tokio = { version = "1.37.0", features = ["time", "rt"] }
tokio = { version = "1.37.0", features = ["time", "rt"], optional = true }
tracing = "0.1.37"
tracing-subscriber = "0.3.18"
tracing-appender = "0.2"
Expand Down
13 changes: 11 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

# Speak-Easy

Speak-Easy is a Rust library that provides logging functionalities with different levels and rotation options built on top of tokio-rs tracing.
Speak-Easy is a Rust library that provides logging functionalities with different levels and rotation options built on top of tracing and compatible with tokio-rs.

## Features

Expand All @@ -21,10 +21,19 @@ First, add the following to your `Cargo.toml`:

```toml
[dependencies]
speak-easy = "0.1.1"
speak-easy = { version = "0.1" }
tokio = { features = ["macros", "rt-multi-thread"], version = "1.37.0" }
```

**Note**

If you want to use Speak-Easy without tokio, you must disable default features:

```toml
[dependencies]
speak-easy = { version = "0.1", default-features = false }
```

Then, use the library in your code like this:


Expand Down
16 changes: 13 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

//! # speak-easy
//!
//! Logging functionalities with different levels and rotation options built on top of tokio-rs tracing.
//! Logging functionalities with different levels and rotation options built on top of tracing and compatible with of tokio-rs
//!
//! ## Features
//!| Feature | Status |
Expand Down Expand Up @@ -32,11 +32,20 @@
//!
//! ```toml
//! [dependencies]
//! speak-easy = "0.1.1"
//! speak-easy = { version = "0.1" }
//! tokio = { features = ["macros", "rt-multi-thread"], version = "1.37.0" }
//! ```
//!
//! **Note**
//!
//! If you want to use Speak-Easy without tokio, you must disable default features:
//!
//! ```toml
//! [dependencies]
//! speak-easy = { version = "0.1", default-features = false }
//! ```
//!
//! Remeber that the `tokio` dependency is required for the `tracing` crate. Your main function should look like this:
//! Your main function should look like this:
//!
//! ```rust
//! #[tokio::main]
Expand Down Expand Up @@ -100,6 +109,7 @@
//!

mod formatter;
mod processor;
pub use tracing::{debug, error, info, trace, warn, Level};
pub mod speak_easy;

Expand Down
51 changes: 51 additions & 0 deletions src/processor.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
use std::time::Duration;
use std::fs;
use std::io;


fn keep_last_logs(directory_path: &str, prefix: &str, holds_num: &usize) -> io::Result<()> {
// Read the directory
let mut entries = fs::read_dir(directory_path)?
.map(|res| res.map(|e| e.path()))
.collect::<Result<Vec<_>, io::Error>>()?;

// Filter the entries to only include files that start with the prefix
entries.retain(|path| {
path.file_name()
.and_then(|name| name.to_str())
.map(|name| name.starts_with(prefix))
.unwrap_or(false)
});

// Sort the entries by modified date in descending order
entries.sort_by_key(|path| fs::metadata(path).and_then(|meta| meta.modified()).unwrap());
entries.reverse();

// Remove all but the last five entries
for path in entries.into_iter().skip(*holds_num) {
fs::remove_file(path)?;
}

Ok(())
}


#[cfg(feature="tokio_async")]
pub fn spawn_processor(directory_path: String, prefix: String, cleanup_interval: u64, keep_last: usize) {
tokio::spawn(async move {
loop {
let _ = keep_last_logs(&directory_path, &prefix, &keep_last);
tokio::time::sleep(Duration::from_secs(cleanup_interval)).await;
}
});
}

#[cfg(not(feature="tokio_async"))]
pub fn spawn_processor(directory_path: String, prefix: String, cleanup_interval: u64, keep_last: usize) {
std::thread::spawn(move || {
loop {
let _ = keep_last_logs(&directory_path, &prefix, &keep_last);
std::thread::sleep(Duration::from_secs(cleanup_interval));
}
});
}
46 changes: 2 additions & 44 deletions src/speak_easy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,7 @@
//!

use crate::{
formatter::LogsFileFormatter,
{Rotation, SpeakConfig},
formatter::LogsFileFormatter, processor::spawn_processor, Rotation, SpeakConfig
};
use tracing::Level;
use tracing_subscriber::{
Expand All @@ -24,11 +23,6 @@ use tracing_subscriber::{
reload,
};

use std::fs;
use std::io;
use std::sync::Arc;
use tokio::time::{sleep, Duration};

pub struct SpeakEasy {}

impl SpeakEasy {
Expand Down Expand Up @@ -73,17 +67,7 @@ impl SpeakEasy {
}

if speak_easy_config.clone().cleanup {
let directory_path = Arc::new(speak_easy_config.directory_path.clone());
let prefix = Arc::new(speak_easy_config.prefix.clone());
let cleanup_interval = Arc::new(speak_easy_config.cleanup_interval);
let holds_num = Arc::new(speak_easy_config.keep_last);

tokio::spawn(async move {
loop {
let _ = SpeakEasy::keep_last_logs(&directory_path, &prefix, &holds_num);
sleep(Duration::from_secs(*cleanup_interval)).await;
}
});
spawn_processor(speak_easy_config.directory_path.to_string(), speak_easy_config.prefix.to_string(), speak_easy_config.cleanup_interval, speak_easy_config.keep_last)
}
}
None => {
Expand All @@ -93,30 +77,4 @@ impl SpeakEasy {
}
};
}

fn keep_last_logs(directory_path: &str, prefix: &str, holds_num: &usize) -> io::Result<()> {
// Read the directory
let mut entries = fs::read_dir(directory_path)?
.map(|res| res.map(|e| e.path()))
.collect::<Result<Vec<_>, io::Error>>()?;

// Filter the entries to only include files that start with the prefix
entries.retain(|path| {
path.file_name()
.and_then(|name| name.to_str())
.map(|name| name.starts_with(prefix))
.unwrap_or(false)
});

// Sort the entries by modified date in descending order
entries.sort_by_key(|path| fs::metadata(path).and_then(|meta| meta.modified()).unwrap());
entries.reverse();

// Remove all but the last five entries
for path in entries.into_iter().skip(*holds_num) {
fs::remove_file(path)?;
}

Ok(())
}
}
Loading