Skip to content

Commit

Permalink
subscriber: Added BoxMakeWriter. (#958)
Browse files Browse the repository at this point in the history
## Motivation

See context from
#776 (comment). This
should unblock the effort to land an appender that can write the same
log line to multiple writers.

## Solution

Implement `BoxMakeWriter` as suggested by @hawkw in the above thread.
  • Loading branch information
SriRamanujam authored Sep 7, 2020
1 parent 11f577a commit 95e4575
Showing 1 changed file with 76 additions and 1 deletion.
77 changes: 76 additions & 1 deletion tracing-subscriber/src/fmt/writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
//!
//! [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html
use std::io;
use io::Write;
use std::{fmt::Debug, io};

/// A type that can create [`io::Write`] instances.
///
Expand Down Expand Up @@ -103,6 +104,80 @@ impl MakeWriter for TestWriter {
}
}

/// A writer that erases the specific [`io::Write`] and [`Makewriter`] types being used.
///
/// This is useful in cases where the concrete type of the writer cannot be known
/// until runtime.
///
/// # Examples
///
/// A function that returns a [`Subscriber`] that will write to either stdout or stderr:
///
/// ```rust
/// # use tracing::Subscriber;
/// # use tracing_subscriber::fmt::writer::BoxMakeWriter;
///
/// fn dynamic_writer(use_stderr: bool) -> impl Subscriber {
/// let writer = if use_stderr {
/// BoxMakeWriter::new(std::io::stderr)
/// } else {
/// BoxMakeWriter::new(std::io::stdout)
/// };
///
/// tracing_subscriber::fmt().with_writer(writer).finish()
/// }
/// ```
///
/// [`MakeWriter`]: trait.MakeWriter.html
/// [`Subscriber`]: https://docs.rs/tracing/latest/tracing/trait.Subscriber.html
/// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html
pub struct BoxMakeWriter {
inner: Box<dyn MakeWriter<Writer = Box<dyn Write>> + Send + Sync>,
}

impl BoxMakeWriter {
/// Constructs a `BoxMakeWriter` wrapping a type implementing [`MakeWriter`].
///
/// [`MakeWriter`]: trait.MakeWriter.html
pub fn new<M>(make_writer: M) -> Self
where
M: MakeWriter + Send + Sync + 'static,
M::Writer: Write + 'static,
{
Self {
inner: Box::new(Boxed(make_writer)),
}
}
}

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

impl MakeWriter for BoxMakeWriter {
type Writer = Box<dyn Write>;

fn make_writer(&self) -> Self::Writer {
self.inner.make_writer()
}
}

struct Boxed<M>(M);

impl<M> MakeWriter for Boxed<M>
where
M: MakeWriter,
M::Writer: Write + 'static,
{
type Writer = Box<dyn Write>;

fn make_writer(&self) -> Self::Writer {
Box::new(self.0.make_writer())
}
}

#[cfg(test)]
mod test {
use super::MakeWriter;
Expand Down

0 comments on commit 95e4575

Please sign in to comment.