Skip to content

Commit

Permalink
file: print an error message if writing to the file fails
Browse files Browse the repository at this point in the history
  • Loading branch information
chensoft committed Mar 7, 2024
1 parent 7993ad2 commit 3fb2fa3
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 11 deletions.
18 changes: 11 additions & 7 deletions HISTORY.md
@@ -1,10 +1,3 @@
## [Unreleased]

### Added

- get logger's plugins and targets
- create directory in FileTarget

### Todo

- predefined fields do not need invoked every time
Expand All @@ -14,6 +7,17 @@
- highlight keywords in console output
- sampling by level

## [0.3.2] - 2024-03-07

### Added

- Retrieve logger's plugins and targets
- Automatically create the directory in FileTarget

### Changed

- Print an error message if writing to the file fails

## [0.3.1] - 2024-02-02

### Changed
Expand Down
9 changes: 8 additions & 1 deletion examples/multi_thread.rs
@@ -1,10 +1,15 @@
#[macro_use] extern crate logkit;

#[tokio::main]
async fn main() {
async fn main() -> anyhow::Result<()> {
let mut logger = logkit::Logger::new(Some(&logkit::StdoutTarget));
logger.mount(logkit::LevelPlugin);
logger.mount(logkit::TimePlugin::from_millis());

let mut sample = std::env::temp_dir();
sample.push("sample.log");
logger.route(logkit::FileTarget::new(sample)?);

logkit::set_default_logger(logger);

let mut handles = vec![];
Expand All @@ -16,4 +21,6 @@ async fn main() {
}

futures::future::join_all(handles).await;

Ok(())
}
1 change: 1 addition & 0 deletions src/define.rs
Expand Up @@ -3,6 +3,7 @@ pub(crate) use std::io::Write;
pub(crate) use std::path::Path;
pub(crate) use std::cell::RefCell;
pub(crate) use parking_lot::Mutex;
pub(crate) use parking_lot::ReentrantMutex;

/// Any support
pub trait Any: std::any::Any {
Expand Down
9 changes: 6 additions & 3 deletions src/target.rs
Expand Up @@ -56,7 +56,7 @@ impl Target for StderrTarget {
/// ```
pub struct FileTarget {
/// file handle
pub file: Mutex<RefCell<std::fs::File>>,
pub file: ReentrantMutex<RefCell<std::fs::File>>,
}

impl FileTarget {
Expand All @@ -66,14 +66,17 @@ impl FileTarget {
std::fs::create_dir_all(dir)?;
}

Ok(Self {file: Mutex::new(RefCell::new(std::fs::OpenOptions::new().create(true).append(true).open(path)?))})
Ok(Self {file: ReentrantMutex::new(RefCell::new(std::fs::OpenOptions::new().create(true).append(true).open(path)?))})
}
}

impl Target for FileTarget {
#[inline]
fn write(&self, buf: &[u8]) {
let file = self.file.lock();
let _ = file.borrow_mut().write_all(buf);
match file.borrow_mut().write_all(buf) {
Ok(_) => {}
Err(err) => { let _ = std::io::stderr().write_all(format!("Error: {}", err).as_bytes()); }
};
}
}

0 comments on commit 3fb2fa3

Please sign in to comment.