structured_logger/
async_json.rs

1// (c) 2023-present, IO Rust. All rights reserved.
2// See the file LICENSE for licensing terms.
3
4//! # Async JSON Writer Implementation
5//!
6//! A [`Writer`] implementation that logs structured values
7//! asynchronous in JSON format to a file, stderr, stdout, or any other destination, base on [`tokio`].
8//! To create a `Box<dyn Writer>` use the [`new_writer`] function.
9//!
10//! Example: <https://github.com/iorust/structured-logger/blob/main/examples/async_log.rs>
11//!
12//! [`tokio`]: https://crates.io/crates/tokio
13//!
14
15use 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
20/// A Writer implementation that writes logs asynchronous in JSON format.
21pub struct AsyncJSONWriter<W: AsyncWrite + Sync + Send + 'static>(Arc<Mutex<Pin<Box<W>>>>);
22
23impl<W: AsyncWrite + Sync + Send + 'static> AsyncJSONWriter<W> {
24    /// Creates a new AsyncJSONWriter instance.
25    pub fn new(w: W) -> Self {
26        Self(Arc::new(Mutex::new(Box::pin(w))))
27    }
28}
29
30/// Implements Writer trait for AsyncJSONWriter.
31impl<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        // must write the LINE FEED character.
36        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                // should never happen, but if it does, we log it.
45                log_failure(format!("AsyncJSONWriter failed to write log: {}", err).as_str());
46            }
47        });
48        Ok(())
49    }
50}
51
52/// Creates a new `Box<dyn Writer>` instance with the AsyncJSONWriter for a given tokio::io::Write instance.
53pub fn new_writer<W: AsyncWrite + Sync + Send + 'static>(w: W) -> Box<dyn Writer> {
54    Box::new(AsyncJSONWriter::new(w))
55}