1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
use parking_lot::Mutex;
use std::{cell::RefCell, collections::BTreeMap, io, io::Write};
use crate::{log_failure, Key, Value, Writer};
pub struct JSONWriter<W: Write + Sync + Send + 'static>(Mutex<RefCell<Box<W>>>);
impl<W: Write + Sync + Send + 'static> JSONWriter<W> {
pub fn new(w: W) -> Self {
Self(Mutex::new(RefCell::new(Box::new(w))))
}
}
impl<W: Write + Sync + Send + 'static> Writer for JSONWriter<W> {
fn write_log(&self, value: &BTreeMap<Key, Value>) -> Result<(), io::Error> {
let mut buf = Vec::with_capacity(256);
serde_json::to_writer(&mut buf, value).map_err(io::Error::from)?;
buf.write_all(b"\n").map_err(io::Error::from)?;
let w = self.0.lock();
if let Ok(mut w) = w.try_borrow_mut() {
w.as_mut().write_all(&buf).map_err(io::Error::from)?;
} else {
log_failure("JSONWriter failed to write log: writer already borrowed");
}
Ok(())
}
}
pub fn new_writer<W: Write + Sync + Send + 'static>(w: W) -> Box<dyn Writer> {
Box::new(JSONWriter::new(w))
}