Skip to content

Commit

Permalink
Add option to provide custom writer to the logger backend (#518)
Browse files Browse the repository at this point in the history
* Add option to provide custom writer to the logger backend

* fmt
  • Loading branch information
zeegomo authored and al8n committed Nov 8, 2023
1 parent 90b2268 commit 44c7509
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions nomos-services/log/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
// std
use futures::StreamExt;
use std::fmt::{Debug, Formatter};
use std::io::Write;
use std::net::SocketAddr;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
// crates
use serde::{Deserialize, Serialize};
use tracing::{error, Level};
Expand All @@ -21,6 +24,37 @@ pub struct Logger {
worker_guard: Option<WorkerGuard>,
}

/// This is a wrapper around a writer to allow cloning which is
/// required by contract by Overwatch for a configuration struct
#[derive(Clone)]
pub struct SharedWriter {
inner: Arc<Mutex<Box<dyn Write + Send + Sync>>>,
}

impl Write for SharedWriter {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.inner.lock().unwrap().write(buf)
}

fn flush(&mut self) -> std::io::Result<()> {
self.inner.lock().unwrap().flush()
}
}

impl SharedWriter {
pub fn new<W: Write + Send + Sync + 'static>(writer: W) -> Self {
Self {
inner: Arc::new(Mutex::new(Box::new(writer))),
}
}
}

impl Debug for SharedWriter {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SharedWriter").finish()
}
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum LoggerBackend {
Gelf {
Expand All @@ -32,6 +66,8 @@ pub enum LoggerBackend {
},
Stdout,
Stderr,
#[serde(skip)]
Writer(SharedWriter),
}

#[derive(Clone, Debug, Serialize, Deserialize)]
Expand Down Expand Up @@ -121,6 +157,7 @@ impl ServiceCore for Logger {
}
LoggerBackend::Stdout => tracing_appender::non_blocking(std::io::stdout()),
LoggerBackend::Stderr => tracing_appender::non_blocking(std::io::stderr()),
LoggerBackend::Writer(writer) => tracing_appender::non_blocking(writer),
};

let layer = tracing_subscriber::fmt::Layer::new()
Expand Down

0 comments on commit 44c7509

Please sign in to comment.