use std::{
io::Write,
sync::{
Mutex,
PoisonError,
},
};
use crate::{
Event,
Reporter,
ReporterError,
};
pub struct JsonLinesReporter<W> {
writer: Mutex<W>,
}
impl<W> JsonLinesReporter<W> {
#[must_use]
pub const fn new(writer: W) -> Self {
Self {
writer: Mutex::new(writer),
}
}
pub fn into_inner(self) -> Result<W, PoisonError<W>> {
self.writer.into_inner()
}
}
impl<W> Reporter for JsonLinesReporter<W>
where
W: Write + Send,
{
fn report(&self, event: &Event) -> Result<(), ReporterError> {
let mut encoded =
serde_json::to_vec(event).map_err(ReporterError::new)?;
encoded.push(b'\n');
let mut writer = self.writer.lock().map_err(|_| {
ReporterError::message("JSON Lines reporter mutex is poisoned")
})?;
writer.write_all(&encoded).map_err(ReporterError::new)
}
}