Optimize logger

This commit is contained in:
Dennis Schwerdel 2020-10-25 21:48:43 +01:00
parent ab79ee58de
commit c5f25ba48e
1 changed files with 7 additions and 7 deletions

View File

@ -56,7 +56,7 @@ use crate::{
struct DualLogger { struct DualLogger {
file: Mutex<Option<File>> file: Option<Mutex<File>>
} }
impl DualLogger { impl DualLogger {
@ -67,9 +67,9 @@ impl DualLogger {
fs::remove_file(path)? fs::remove_file(path)?
} }
let file = File::create(path)?; let file = File::create(path)?;
Ok(DualLogger { file: Mutex::new(Some(file)) }) Ok(DualLogger { file: Some(Mutex::new(file)) })
} else { } else {
Ok(DualLogger { file: Mutex::new(None) }) Ok(DualLogger { file: None })
} }
} }
} }
@ -84,8 +84,8 @@ impl log::Log for DualLogger {
fn log(&self, record: &log::Record) { fn log(&self, record: &log::Record) {
if self.enabled(record.metadata()) { if self.enabled(record.metadata()) {
println!("{} - {}", record.level(), record.args()); println!("{} - {}", record.level(), record.args());
let mut file = self.file.lock().expect("Lock poisoned"); if let Some(ref file) = self.file {
if let Some(ref mut file) = *file { let mut file = file.lock().expect("Lock poisoned");
let time = time::OffsetDateTime::now_local().format("%F %T"); let time = time::OffsetDateTime::now_local().format("%F %T");
writeln!(file, "{} - {} - {}", time, record.level(), record.args()) writeln!(file, "{} - {} - {}", time, record.level(), record.args())
.expect("Failed to write to logfile"); .expect("Failed to write to logfile");
@ -95,8 +95,8 @@ impl log::Log for DualLogger {
#[inline] #[inline]
fn flush(&self) { fn flush(&self) {
let mut file = self.file.lock().expect("Lock poisoned"); if let Some(ref file) = self.file {
if let Some(ref mut file) = *file { let mut file = file.lock().expect("Lock poisoned");
try_fail!(file.flush(), "Logging error: {}"); try_fail!(file.flush(), "Logging error: {}");
} }
} }