structured_logger/
json.rs

1// (c) 2023-present, IO Rust. All rights reserved.
2// See the file LICENSE for licensing terms.
3
4//! # Sync JSON Writer Implementation
5//!
6//! A [`Writer`] implementation that logs structured values
7//! synchronous in JSON format to a file, stderr, stdout, or any other destination.
8//! To create a `Box<dyn Writer>` use the [`new_writer`] function.
9//!
10//! Example: <https://github.com/iorust/structured-logger/blob/main/examples/simple.rs>
11//!
12
13use parking_lot::Mutex;
14use std::{cell::RefCell, collections::BTreeMap, io, io::Write};
15
16use crate::{log_failure, Key, Value, Writer};
17/// A Writer implementation that writes logs in JSON format.
18pub struct JSONWriter<W: Write + Sync + Send + 'static>(Mutex<RefCell<Box<W>>>);
19
20impl<W: Write + Sync + Send + 'static> JSONWriter<W> {
21    /// Creates a new JSONWriter instance.
22    pub fn new(w: W) -> Self {
23        Self(Mutex::new(RefCell::new(Box::new(w))))
24    }
25}
26
27/// Implements Writer trait for JSONWriter.
28impl<W: Write + Sync + Send + 'static> Writer for JSONWriter<W> {
29    fn write_log(&self, value: &BTreeMap<Key, Value>) -> Result<(), io::Error> {
30        let mut buf = Vec::with_capacity(256);
31        serde_json::to_writer(&mut buf, value).map_err(io::Error::from)?;
32        // must write the LINE FEED character.
33        buf.write_all(b"\n")?;
34
35        let w = self.0.lock();
36        if let Ok(mut w) = w.try_borrow_mut() {
37            w.as_mut().write_all(&buf)?;
38        } else {
39            // should never happen, but if it does, we log it.
40            log_failure("JSONWriter failed to write log: writer already borrowed");
41        }
42        Ok(())
43    }
44}
45
46/// Creates a new `Box<dyn Writer>` instance with the JSONWriter for a given std::io::Write instance.
47pub fn new_writer<W: Write + Sync + Send + 'static>(w: W) -> Box<dyn Writer> {
48    Box::new(JSONWriter::new(w))
49}