Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

appender: Added BoxMakeWriter. #958

Merged
merged 4 commits into from
Sep 7, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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.
///
SriRamanujam marked this conversation as resolved.
Show resolved Hide resolved
/// # 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