structured_logger/
async_json.rs1use std::{collections::BTreeMap, io, io::Write, pin::Pin, sync::Arc};
16use tokio::{io::AsyncWrite, sync::Mutex};
17
18use crate::{log_failure, Key, Value, Writer};
19
20pub struct AsyncJSONWriter<W: AsyncWrite + Sync + Send + 'static>(Arc<Mutex<Pin<Box<W>>>>);
22
23impl<W: AsyncWrite + Sync + Send + 'static> AsyncJSONWriter<W> {
24 pub fn new(w: W) -> Self {
26 Self(Arc::new(Mutex::new(Box::pin(w))))
27 }
28}
29
30impl<W: AsyncWrite + Sync + Send + 'static> Writer for AsyncJSONWriter<W> {
32 fn write_log(&self, value: &BTreeMap<Key, Value>) -> Result<(), io::Error> {
33 let mut buf = Vec::with_capacity(256);
34 serde_json::to_writer(&mut buf, value).map_err(io::Error::from)?;
35 buf.write_all(b"\n")?;
37
38 let w = self.0.clone();
39 tokio::spawn(async move {
40 use tokio::io::AsyncWriteExt;
41
42 let mut w = w.lock().await;
43 if let Err(err) = w.as_mut().write_all(&buf).await {
44 log_failure(format!("AsyncJSONWriter failed to write log: {}", err).as_str());
46 }
47 });
48 Ok(())
49 }
50}
51
52pub fn new_writer<W: AsyncWrite + Sync + Send + 'static>(w: W) -> Box<dyn Writer> {
54 Box::new(AsyncJSONWriter::new(w))
55}