You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
1.1 KiB
Rust

use crate::error::Error;
pub use log::{debug, error, info, set_logger, set_max_level, trace, warn, LevelFilter};
use std::{
fs::File,
io,
path::Path,
sync::{Arc, Mutex},
};
use log::{Metadata, Record};
pub struct Log<W> {
out: Arc<Mutex<W>>,
}
impl Log<File> {
pub fn file<P: AsRef<Path>>(p: P) -> Result<Self, Error> {
let f = File::options().append(true).create(true).open(p)?;
Ok(Self {
out: Arc::new(Mutex::new(f)),
})
}
}
impl<W> Log<W>
where
W: io::Write,
{
pub fn from_writer(w: W) -> Self {
Self {
out: Arc::new(Mutex::new(w)),
}
}
}
impl<W> log::Log for Log<W>
where
W: io::Write + Send,
{
fn enabled(&self, _metadata: &Metadata) -> bool {
true
}
fn log(&self, record: &Record) {
if self.enabled(record.metadata()) {
if let Ok(out) = self.out.lock().as_deref_mut() {
_ = write!(out, "{} - {}\n", record.level(), record.args());
}
}
}
fn flush(&self) {
if let Ok(out) = self.out.lock().as_deref_mut() {
_ = out.flush();
}
}
}