fix: move events writer to individual thread (#669)
parent
c55e4481ba
commit
88d2617a34
|
|
@ -1,15 +1,22 @@
|
||||||
use std::{
|
use std::{
|
||||||
fs,
|
fs,
|
||||||
io::{BufWriter, Write},
|
io::{BufWriter, Write},
|
||||||
sync::Mutex,
|
time::Duration,
|
||||||
};
|
};
|
||||||
|
|
||||||
use chrono::Utc;
|
use chrono::Utc;
|
||||||
use lazy_static::lazy_static;
|
use lazy_static::lazy_static;
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
|
use tokio::{
|
||||||
|
sync::mpsc::{unbounded_channel, UnboundedSender},
|
||||||
|
time::{self},
|
||||||
|
};
|
||||||
|
|
||||||
lazy_static! {
|
lazy_static! {
|
||||||
static ref WRITER: Mutex<BufWriter<fs::File>> = {
|
static ref WRITER: UnboundedSender<String> = {
|
||||||
|
let (tx, mut rx) = unbounded_channel::<String>();
|
||||||
|
|
||||||
|
tokio::spawn(async move {
|
||||||
let events_dir = crate::path::events_dir();
|
let events_dir = crate::path::events_dir();
|
||||||
std::fs::create_dir_all(events_dir.as_path()).ok();
|
std::fs::create_dir_all(events_dir.as_path()).ok();
|
||||||
|
|
||||||
|
|
@ -23,7 +30,26 @@ lazy_static! {
|
||||||
.ok()
|
.ok()
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
Mutex::new(BufWriter::new(file))
|
let mut writer = BufWriter::new(file);
|
||||||
|
let mut interval = time::interval(Duration::from_secs(5));
|
||||||
|
|
||||||
|
loop {
|
||||||
|
tokio::select! {
|
||||||
|
content = rx.recv() => {
|
||||||
|
if let Some(content) = content {
|
||||||
|
writeln!(&mut writer, "{}", content).unwrap();
|
||||||
|
} else {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ = interval.tick() => {
|
||||||
|
writer.flush().unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
tx
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -75,18 +101,13 @@ struct Log<'a> {
|
||||||
|
|
||||||
impl Event<'_> {
|
impl Event<'_> {
|
||||||
pub fn log(&self) {
|
pub fn log(&self) {
|
||||||
let mut writer = WRITER.lock().unwrap();
|
let content = serdeconv::to_json_string(&Log {
|
||||||
|
|
||||||
serdeconv::to_json_writer(
|
|
||||||
&Log {
|
|
||||||
ts: timestamp(),
|
ts: timestamp(),
|
||||||
event: self,
|
event: self,
|
||||||
},
|
})
|
||||||
writer.by_ref(),
|
|
||||||
)
|
|
||||||
.unwrap();
|
.unwrap();
|
||||||
writeln!(writer).unwrap();
|
|
||||||
writer.flush().unwrap();
|
WRITER.send(content).unwrap();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue