From 4bf3d0000c9b8ed7b372a370e068c07a4a982c9d Mon Sep 17 00:00:00 2001 From: Eliza Weisman Date: Fri, 25 Jun 2021 13:30:37 -0700 Subject: [PATCH] subscriber: add `MakeWriter` combinators (#1274) This backports #1274 from `master`. Depends on #1141. This branch adds a `MakeWriterExt` trait which adds a number of combinators for composing multiple types implementing `MakeWriter`. `MakeWriter`s can now be teed together, filtered with minimum and maximum levels, filtered with a `Metadata` predicate, and combined with a fallback for when a writer is _not_ made for a particular `Metadata`. I've also added a `MakeWriter` impl for `Arc` when `&W` implements `Write`. This enables `File`s to be used as `MakeWriter`s similarly to how we will be able to in 0.3, with the additional overhead of having to do ref-counting because we can't return a reference from `MakeWriter` until the next breaking change. Signed-off-by: Eliza Weisman --- tracing-subscriber/src/fmt/writer.rs | 996 +++++++++++++++++++++++++-- tracing-subscriber/src/layer.rs | 2 +- tracing-subscriber/src/prelude.rs | 4 + 3 files changed, 958 insertions(+), 44 deletions(-) diff --git a/tracing-subscriber/src/fmt/writer.rs b/tracing-subscriber/src/fmt/writer.rs index ed7c45e4a2..ba04ba817d 100644 --- a/tracing-subscriber/src/fmt/writer.rs +++ b/tracing-subscriber/src/fmt/writer.rs @@ -4,6 +4,7 @@ use std::{ fmt::Debug, io::{self, Write}, + sync::Arc, }; use tracing_core::Metadata; @@ -197,15 +198,256 @@ pub trait MakeWriter { } } -impl MakeWriter for F -where - F: Fn() -> W, - W: io::Write, -{ - type Writer = W; +/// Extension trait adding combinators for working with types implementing +/// [`MakeWriter`]. +/// +/// This is not intended to be implemented directly for user-defined +/// [`MakeWriter`]s; instead, it should be imported when the desired methods are +/// used. +pub trait MakeWriterExt: MakeWriter { + /// Wraps `self` and returns a [`MakeWriter`] that will only write output + /// for events at or below the provided verbosity [`Level`]. For instance, + /// `Level::TRACE` is considered to be _more verbose` than `Level::INFO`. + /// + /// Events whose level is more verbose than `level` will be ignored, and no + /// output will be written. + /// + /// # Examples + /// + /// ``` + /// use tracing::Level; + /// use tracing_subscriber::fmt::writer::MakeWriterExt; + /// + /// // Construct a writer that outputs events to `stderr` only if the span or + /// // event's level is >= WARN (WARN and ERROR). + /// let mk_writer = std::io::stderr.with_max_level(Level::WARN); + /// + /// tracing_subscriber::fmt().with_writer(mk_writer).init(); + /// ``` + /// + /// Writing the `ERROR` and `WARN` levels to `stderr`, and everything else + /// to `stdout`: + /// + /// ``` + /// # use tracing::Level; + /// # use tracing_subscriber::fmt::writer::MakeWriterExt; + /// + /// let mk_writer = std::io::stderr + /// .with_max_level(Level::WARN) + /// .or_else(std::io::stdout); + /// + /// tracing_subscriber::fmt().with_writer(mk_writer).init(); + /// ``` + /// + /// Writing the `ERROR` level to `stderr`, the `INFO` and `WARN` levels to + /// `stdout`, and the `INFO` and DEBUG` levels to a file: + /// + /// ``` + /// # use tracing::Level; + /// # use tracing_subscriber::fmt::writer::MakeWriterExt; + /// use std::{sync::Arc, fs::File}; + /// # // don't actually create the file when running the tests. + /// # fn docs() -> std::io::Result<()> { + /// let debug_log = Arc::new(File::create("debug.log")?); + /// + /// let mk_writer = std::io::stderr + /// .with_max_level(Level::ERROR) + /// .or_else(std::io::stdout + /// .with_max_level(Level::INFO) + /// .and(debug_log.with_max_level(Level::DEBUG)) + /// ); + /// + /// tracing_subscriber::fmt().with_writer(mk_writer).init(); + /// # Ok(()) } + /// ``` + /// + /// [`Level`]: tracing_core::Level + /// [`io::Write`]: std::io::Write + fn with_max_level(self, level: tracing_core::Level) -> WithMaxLevel + where + Self: Sized, + { + WithMaxLevel::new(self, level) + } - fn make_writer(&self) -> Self::Writer { - (self)() + /// Wraps `self` and returns a [`MakeWriter`] that will only write output + /// for events at or above the provided verbosity [`Level`]. + /// + /// Events whose level is less verbose than `level` will be ignored, and no + /// output will be written. + /// + /// # Examples + /// + /// ``` + /// use tracing::Level; + /// use tracing_subscriber::fmt::writer::MakeWriterExt; + /// + /// // Construct a writer that outputs events to `stdout` only if the span or + /// // event's level is <= DEBUG (DEBUG and TRACE). + /// let mk_writer = std::io::stdout.with_min_level(Level::DEBUG); + /// + /// tracing_subscriber::fmt().with_writer(mk_writer).init(); + /// ``` + /// This can be combined with [`MakeWriterExt::with_max_level`] to write + /// only within a range of levels: + /// + /// ``` + /// # use tracing::Level; + /// # use tracing_subscriber::fmt::writer::MakeWriterExt; + /// // Only write the `DEBUG` and `INFO` levels to stdout. + /// let mk_writer = std::io::stdout + /// .with_max_level(Level::DEBUG) + /// .with_min_level(Level::INFO) + /// // Write the `WARN` and `ERROR` levels to stderr. + /// .and(std::io::stderr.with_min_level(Level::WARN)); + /// + /// tracing_subscriber::fmt().with_writer(mk_writer).init(); + /// ``` + /// [`Level`]: tracing_core::Level + /// [`io::Write`]: std::io::Write + fn with_min_level(self, level: tracing_core::Level) -> WithMinLevel + where + Self: Sized, + { + WithMinLevel::new(self, level) + } + + /// Wraps `self` with a predicate that takes a span or event's [`Metadata`] + /// and returns a `bool`. The returned [`MakeWriter`]'s + /// [`MakeWriter::make_writer_for`][mwf] method will check the predicate to + /// determine if a writer should be produced for a given span or event. + /// + /// If the predicate returns `false`, the wrapped [`MakeWriter`]'s + /// [`make_writer_for`][mwf] will return [`OptionalWriter::none`]. + /// Otherwise, it calls the wrapped [`MakeWriter`]'s + /// [`make_writer_for`][mwf] method, and returns the produced writer. + /// + /// This can be used to filter an output based on arbitrary [`Metadata`] + /// parameters. + /// + /// # Examples + /// + /// Writing events with a specific target to an HTTP access log, and other + /// events to stdout: + /// + /// ``` + /// use tracing_subscriber::fmt::writer::MakeWriterExt; + /// use std::{sync::Arc, fs::File}; + /// # // don't actually create the file when running the tests. + /// # fn docs() -> std::io::Result<()> { + /// let access_log = Arc::new(File::create("access.log")?); + /// + /// let mk_writer = access_log + /// // Only write events with the target "http::access_log" to the + /// // access log file. + /// .with_filter(|meta| meta.target() == "http::access_log") + /// // Write events with all other targets to stdout. + /// .or_else(std::io::stdout); + /// + /// tracing_subscriber::fmt().with_writer(mk_writer).init(); + /// # Ok(()) + /// # } + /// ``` + /// + /// Conditionally enabling or disabling a log file: + /// ``` + /// use tracing_subscriber::fmt::writer::MakeWriterExt; + /// use std::{ + /// sync::{Arc, atomic::{AtomicBool, Ordering}}, + /// fs::File, + /// }; + /// + /// static DEBUG_LOG_ENABLED: AtomicBool = AtomicBool::new(false); + /// + /// # // don't actually create the file when running the tests. + /// # fn docs() -> std::io::Result<()> { + /// // Create the debug log file + /// let debug_file = Arc::new(File::create("debug.log")?) + /// // Enable the debug log only if the flag is enabled. + /// .with_filter(|_| DEBUG_LOG_ENABLED.load(Ordering::Acquire)); + /// + /// // Always write to stdout + /// let mk_writer = std::io::stdout + /// // Write to the debug file if it's enabled + /// .and(debug_file); + /// + /// tracing_subscriber::fmt().with_writer(mk_writer).init(); + /// + /// // ... + /// + /// // Later, we can toggle on or off the debug log file. + /// DEBUG_LOG_ENABLED.store(true, Ordering::Release); + /// # Ok(()) + /// # } + /// ``` + /// + /// [`Metadata`]: tracing_core::Metadata + /// [mwf]: MakeWriter::make_writer_for + fn with_filter(self, filter: F) -> WithFilter + where + Self: Sized, + F: Fn(&Metadata<'_>) -> bool, + { + WithFilter::new(self, filter) + } + + /// Combines `self` with another type implementing [`MakeWriter`], returning + /// a new [`MakeWriter`] that produces [writers] that write to *both* + /// outputs. + /// + /// If writing to either writer returns an error, the returned writer will + /// return that error. However, both writers will still be written to before + /// the error is returned, so it is possible for one writer to fail while + /// the other is written to successfully. + /// + /// # Examples + /// + /// ``` + /// use tracing_subscriber::fmt::writer::MakeWriterExt; + /// + /// // Construct a writer that outputs events to `stdout` *and* `stderr`. + /// let mk_writer = std::io::stdout.and(std::io::stderr); + /// + /// tracing_subscriber::fmt().with_writer(mk_writer).init(); + /// ``` + /// + /// `and` can be used in conjunction with filtering combinators. For + /// example, if we want to write to a number of outputs depending on + fn and(self, other: B) -> Tee + where + Self: Sized, + B: MakeWriter + Sized, + { + Tee::new(self, other) + } + + /// Combines `self` with another type implementing [`MakeWriter`], returning + /// a new [`MakeWriter`] that calls `other`'s [`make_writer`] if `self`'s + /// `make_writer` returns [`OptionalWriter::none`]. + /// + /// # Examples + /// + /// ``` + /// use tracing::Level; + /// use tracing_subscriber::fmt::writer::MakeWriterExt; + /// + /// // Produces a writer that writes to `stderr` if the level is >= WARN, + /// // or returns `OptionalWriter::none()` otherwise. + /// let stderr = std::io::stderr.with_max_level(Level::WARN); + /// + /// // If the `stderr` `MakeWriter` is disabled by the max level filter, + /// // write to stdout instead: + /// let mk_writer = stderr.or_else(std::io::stdout); + /// + /// tracing_subscriber::fmt().with_writer(mk_writer).init(); + /// ``` + fn or_else(self, other: B) -> OrElse + where + Self: MakeWriter> + Sized, + B: MakeWriter + Sized, + W: Write, + { + OrElse::new(self, other) } } @@ -231,6 +473,156 @@ pub struct TestWriter { _p: (), } +/// 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() +/// } +/// ``` +/// +/// [`Subscriber`]: tracing::Subscriber +/// [`io::Write`]: std::io::Write +pub struct BoxMakeWriter { + inner: Box> + Send + Sync>, + name: &'static str, +} + +/// A [writer] that is one of two types implementing [`io::Write`][writer]. +/// +/// This may be used by [`MakeWriter`] implementations that may conditionally +/// return one of two writers. +/// +/// [writer]: std::io::Write +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub enum EitherWriter { + /// A writer of type `A`. + A(A), + /// A writer of type `B`. + B(B), +} + +/// A [writer] which may or may not be enabled. +/// +/// This may be used by [`MakeWriter`] implementations that wish to +/// conditionally enable or disable the returned writer based on a span or +/// event's [`Metadata`]. +/// +/// [writer]: std::io::Write +pub type OptionalWriter = EitherWriter; + +/// A [`MakeWriter`] combinator that only returns an enabled [writer] for spans +/// and events with metadata at or below a specified verbosity [`Level`]. +/// +/// This is returned by the [`MakeWriterExt::with_max_level] method. See the +/// method documentation for details. +/// +/// [writer]: std::io::Write +/// [`Level`]: tracing_core::Level +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub struct WithMaxLevel { + make: M, + level: tracing_core::Level, +} + +/// A [`MakeWriter`] combinator that only returns an enabled [writer] for spans +/// and events with metadata at or above a specified verbosity [`Level`]. +/// +/// This is returned by the [`MakeWriterExt::with_min_level] method. See the +/// method documentation for details. +/// +/// [writer]: std::io::Write +/// [`Level`]: tracing_core::Level +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub struct WithMinLevel { + make: M, + level: tracing_core::Level, +} + +/// A [`MakeWriter`] combinator that wraps a [`MakeWriter`] with a predicate for +/// span and event [`Metadata`], so that the [`MakeWriterExt::make_writer_for`] +/// method returns [`OptionalWriter::some`] when the predicate returns `true`, +/// and [`OptionalWriter::none`] when the predicate returns `false`. +/// +/// This is returned by the [`MakeWriterExt::with_filter`] method. See the +/// method documentation for details. +/// +/// [`Metadata`]: tracing_core::Metadata +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub struct WithFilter { + make: M, + filter: F, +} + +/// Combines a [`MakeWriter`] that returns an [`OptionalWriter`] with another +/// [`MakeWriter`], so that the second [`MakeWriter`] is used when the first +/// [`MakeWriter`] returns [`OptionalWriter::none`]. +/// +/// This is returned by the [`MakeWriterExt::or_else] method. See the +/// method documentation for details. +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub struct OrElse { + inner: A, + or_else: B, +} + +/// Combines two types implementing [`MakeWriter`] (or [`std::io::Write`]) to +/// produce a writer that writes to both [`MakeWriter`]'s returned writers. +/// +/// This is returned by the [`MakeWriterExt::and`] method. See the method +/// documentation for details. +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub struct Tee { + a: A, + b: B, +} + +impl MakeWriter for F +where + F: Fn() -> W, + W: io::Write, +{ + type Writer = W; + + fn make_writer(&self) -> Self::Writer { + (self)() + } +} + +impl MakeWriter for Arc +where + for<'a> &'a W: io::Write, +{ + type Writer = ArcWriter; + fn make_writer(&self) -> Self::Writer { + ArcWriter(self.clone()) + } +} + +/// Implements [`std::io::Write`] for an [`Arc`] where `&W: Write`. +/// +/// This is an implementation detail of the [`MakeWriter`] impl for [`Arc`]. +#[derive(Clone, Debug)] +pub struct ArcWriter(Arc); + +// === impl TestWriter === + impl TestWriter { /// Returns a new `TestWriter` with the default configuration. pub fn new() -> Self { @@ -258,37 +650,6 @@ 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> + Send + Sync>, -} - impl BoxMakeWriter { /// Constructs a `BoxMakeWriter` wrapping a type implementing [`MakeWriter`]. /// @@ -300,13 +661,16 @@ impl BoxMakeWriter { { Self { inner: Box::new(Boxed(make_writer)), + name: std::any::type_name::(), } } } impl Debug for BoxMakeWriter { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.pad("BoxMakeWriter { ... }") + f.debug_tuple("BoxMakeWriter") + .field(&format_args!("<{}>", self.name)) + .finish() } } @@ -342,15 +706,357 @@ where } } +// === impl EitherWriter === + +impl io::Write for EitherWriter +where + A: io::Write, + B: io::Write, +{ + #[inline] + fn write(&mut self, buf: &[u8]) -> io::Result { + match self { + EitherWriter::A(a) => a.write(buf), + EitherWriter::B(b) => b.write(buf), + } + } + + #[inline] + fn flush(&mut self) -> io::Result<()> { + match self { + EitherWriter::A(a) => a.flush(), + EitherWriter::B(b) => b.flush(), + } + } + + #[inline] + fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result { + match self { + EitherWriter::A(a) => a.write_vectored(bufs), + EitherWriter::B(b) => b.write_vectored(bufs), + } + } + + #[inline] + fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { + match self { + EitherWriter::A(a) => a.write_all(buf), + EitherWriter::B(b) => b.write_all(buf), + } + } + + #[inline] + fn write_fmt(&mut self, fmt: std::fmt::Arguments<'_>) -> io::Result<()> { + match self { + EitherWriter::A(a) => a.write_fmt(fmt), + EitherWriter::B(b) => b.write_fmt(fmt), + } + } +} + +impl OptionalWriter { + /// Returns a [disabled writer]. + /// + /// Any bytes written to the returned writer are discarded. + /// + /// This is equivalent to returning [`Option::None`]. + /// + /// [disabled writer]: std::io::sink + #[inline] + pub fn none() -> Self { + EitherWriter::B(std::io::sink()) + } + + /// Returns an enabled writer of type `T`. + /// + /// This is equivalent to returning [`Option::Some`]. + #[inline] + pub fn some(t: T) -> Self { + EitherWriter::A(t) + } +} + +impl From> for OptionalWriter { + #[inline] + fn from(opt: Option) -> Self { + match opt { + Some(writer) => Self::some(writer), + None => Self::none(), + } + } +} + +// === impl WithMaxLevel === + +impl WithMaxLevel { + /// Wraps the provided [`MakeWriter`] with a maximum [`Level`], so that it + /// returns [`OptionalWriter::none`] for spans and events whose level is + /// more verbose than the maximum level. + /// + /// See [`MakeWriterExt::with_max_level`] for details. + /// + /// [`Level`]: tracing_core::Level + pub fn new(make: M, level: tracing_core::Level) -> Self { + Self { make, level } + } +} + +impl MakeWriter for WithMaxLevel { + type Writer = OptionalWriter; + + #[inline] + fn make_writer(&self) -> Self::Writer { + // If we don't know the level, assume it's disabled. + OptionalWriter::none() + } + + #[inline] + fn make_writer_for(&self, meta: &Metadata<'_>) -> Self::Writer { + if meta.level() <= &self.level { + return OptionalWriter::some(self.make.make_writer_for(meta)); + } + OptionalWriter::none() + } +} + +// === impl WithMinLevel === + +impl WithMinLevel { + /// Wraps the provided [`MakeWriter`] with a minimum [`Level`], so that it + /// returns [`OptionalWriter::none`] for spans and events whose level is + /// less verbose than the maximum level. + /// + /// See [`MakeWriterExt::with_min_level`] for details. + /// + /// [`Level`]: tracing_core::Level + pub fn new(make: M, level: tracing_core::Level) -> Self { + Self { make, level } + } +} + +impl MakeWriter for WithMinLevel { + type Writer = OptionalWriter; + + #[inline] + fn make_writer(&self) -> Self::Writer { + // If we don't know the level, assume it's disabled. + OptionalWriter::none() + } + + #[inline] + fn make_writer_for(&self, meta: &Metadata<'_>) -> Self::Writer { + if meta.level() >= &self.level { + return OptionalWriter::some(self.make.make_writer_for(meta)); + } + OptionalWriter::none() + } +} + +// ==== impl WithFilter === + +impl WithFilter { + /// Wraps `make` with the provided `filter`, returning a [`MakeWriter`] that + /// will call `make.make_writer_for()` when `filter` returns `true` for a + /// span or event's [`Metadata`], and returns a [`sink`] otherwise. + /// + /// See [`MakeWriterExt::with_filter`] for details. + /// + /// [`Metadata`]: tracing_core::Metadata + /// [`sink`]: std::io::sink + pub fn new(make: M, filter: F) -> Self + where + F: Fn(&Metadata<'_>) -> bool, + { + Self { make, filter } + } +} + +impl MakeWriter for WithFilter +where + M: MakeWriter, + F: Fn(&Metadata<'_>) -> bool, +{ + type Writer = OptionalWriter; + + #[inline] + fn make_writer(&self) -> Self::Writer { + OptionalWriter::some(self.make.make_writer()) + } + + #[inline] + fn make_writer_for(&self, meta: &Metadata<'_>) -> Self::Writer { + if (self.filter)(meta) { + OptionalWriter::some(self.make.make_writer_for(meta)) + } else { + OptionalWriter::none() + } + } +} + +// === impl Tee === + +impl Tee { + /// Combines two types implementing [`MakeWriter`], returning + /// a new [`MakeWriter`] that produces [writers] that write to *both* + /// outputs. + /// + /// See the documentation for [`MakeWriterExt::and`] for details. + pub fn new(a: A, b: B) -> Self { + Self { a, b } + } +} + +impl MakeWriter for Tee +where + A: MakeWriter, + B: MakeWriter, +{ + type Writer = Tee; + + #[inline] + fn make_writer(&self) -> Self::Writer { + Tee::new(self.a.make_writer(), self.b.make_writer()) + } + + #[inline] + fn make_writer_for(&self, meta: &Metadata<'_>) -> Self::Writer { + Tee::new(self.a.make_writer_for(meta), self.b.make_writer_for(meta)) + } +} + +macro_rules! impl_tee { + ($self_:ident.$f:ident($($arg:ident),*)) => { + { + let res_a = $self_.a.$f($($arg),*); + let res_b = $self_.b.$f($($arg),*); + (res_a?, res_b?) + } + } +} + +impl io::Write for Tee +where + A: io::Write, + B: io::Write, +{ + #[inline] + fn write(&mut self, buf: &[u8]) -> io::Result { + let (a, b) = impl_tee!(self.write(buf)); + Ok(std::cmp::max(a, b)) + } + + #[inline] + fn flush(&mut self) -> io::Result<()> { + impl_tee!(self.flush()); + Ok(()) + } + + #[inline] + fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result { + let (a, b) = impl_tee!(self.write_vectored(bufs)); + Ok(std::cmp::max(a, b)) + } + + #[inline] + fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { + impl_tee!(self.write_all(buf)); + Ok(()) + } + + #[inline] + fn write_fmt(&mut self, fmt: std::fmt::Arguments<'_>) -> io::Result<()> { + impl_tee!(self.write_fmt(fmt)); + Ok(()) + } +} + +// === impl OrElse === + +impl OrElse { + /// Combines + pub fn new(inner: A, or_else: B) -> Self + where + A: MakeWriter>, + B: MakeWriter, + W: Write, + { + Self { inner, or_else } + } +} + +impl MakeWriter for OrElse +where + A: MakeWriter>, + B: MakeWriter, + W: io::Write, +{ + type Writer = EitherWriter; + + #[inline] + fn make_writer(&self) -> Self::Writer { + match self.inner.make_writer() { + EitherWriter::A(writer) => EitherWriter::A(writer), + EitherWriter::B(_) => EitherWriter::B(self.or_else.make_writer()), + } + } + + #[inline] + fn make_writer_for(&self, meta: &Metadata<'_>) -> Self::Writer { + match self.inner.make_writer_for(meta) { + EitherWriter::A(writer) => EitherWriter::A(writer), + EitherWriter::B(_) => EitherWriter::B(self.or_else.make_writer_for(meta)), + } + } +} + +// === impl ArcWriter === + +impl io::Write for ArcWriter +where + for<'a> &'a W: io::Write, +{ + #[inline] + fn write(&mut self, buf: &[u8]) -> io::Result { + (&*self.0).write(buf) + } + + #[inline] + fn flush(&mut self) -> io::Result<()> { + (&*self.0).flush() + } + + #[inline] + fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result { + (&*self.0).write_vectored(bufs) + } + + #[inline] + fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { + (&*self.0).write_all(buf) + } + + #[inline] + fn write_fmt(&mut self, fmt: std::fmt::Arguments<'_>) -> io::Result<()> { + (&*self.0).write_fmt(fmt) + } +} + +// === blanket impls === + +impl MakeWriterExt for M where M: MakeWriter {} + #[cfg(test)] mod test { - use super::MakeWriter; + use super::*; use crate::fmt::format::Format; use crate::fmt::test::{MockMakeWriter, MockWriter}; use crate::fmt::Subscriber; use lazy_static::lazy_static; - use std::sync::Mutex; - use tracing::error; + use std::sync::{ + atomic::{AtomicBool, Ordering}, + Mutex, + }; + use tracing::{debug, error, info, trace, warn, Level}; use tracing_core::dispatcher::{self, Dispatch}; fn test_writer(make_writer: T, msg: &str, buf: &Mutex>) @@ -386,6 +1092,19 @@ mod test { assert!(actual.contains(expected.as_str())); } + fn has_lines(buf: &Mutex>, msgs: &[(tracing::Level, &str)]) { + let actual = String::from_utf8(buf.try_lock().unwrap().to_vec()).unwrap(); + let mut expected_lines = msgs.iter(); + for line in actual.lines() { + let line = dbg!(line).trim(); + let (level, msg) = expected_lines + .next() + .unwrap_or_else(|| panic!("expected no more lines, but got: {:?}", line)); + let expected = format!("{} {}: {}", level, module_path!(), msg); + assert_eq!(line, expected.as_str()); + } + } + #[test] fn custom_writer_closure() { lazy_static! { @@ -407,4 +1126,195 @@ mod test { let msg = "my custom writer struct error"; test_writer(make_writer, msg, &BUF); } + + #[test] + fn combinators_level_filters() { + lazy_static! { + static ref INFO_BUF: Mutex> = Mutex::new(vec![]); + static ref DEBUG_BUF: Mutex> = Mutex::new(vec![]); + static ref WARN_BUF: Mutex> = Mutex::new(vec![]); + static ref ERR_BUF: Mutex> = Mutex::new(vec![]); + } + + let info = MockMakeWriter::new(&INFO_BUF); + let debug = MockMakeWriter::new(&DEBUG_BUF); + let warn = MockMakeWriter::new(&WARN_BUF); + let err = MockMakeWriter::new(&ERR_BUF); + + let make_writer = info + .with_max_level(Level::INFO) + .and(debug.with_max_level(Level::DEBUG)) + .and(warn.with_max_level(Level::WARN)) + .and(err.with_max_level(Level::ERROR)); + + let c = { + #[cfg(feature = "ansi")] + let f = Format::default().without_time().with_ansi(false); + #[cfg(not(feature = "ansi"))] + let f = Format::default().without_time(); + Subscriber::builder() + .event_format(f) + .with_writer(make_writer) + .with_max_level(Level::TRACE) + .finish() + }; + + let _s = tracing::subscriber::set_default(c); + + trace!("trace"); + debug!("debug"); + info!("info"); + warn!("warn"); + error!("error"); + + let all_lines = [ + (Level::TRACE, "trace"), + (Level::DEBUG, "debug"), + (Level::INFO, "info"), + (Level::WARN, "warn"), + (Level::ERROR, "error"), + ]; + + println!("max level debug"); + has_lines(&DEBUG_BUF, &all_lines[1..]); + + println!("max level info"); + has_lines(&INFO_BUF, &all_lines[2..]); + + println!("max level warn"); + has_lines(&WARN_BUF, &all_lines[3..]); + + println!("max level error"); + has_lines(&ERR_BUF, &all_lines[4..]); + } + + #[test] + fn combinators_or_else() { + lazy_static! { + static ref SOME_BUF: Mutex> = Mutex::new(vec![]); + static ref OR_ELSE_BUF: Mutex> = Mutex::new(vec![]); + } + + let some = MockMakeWriter::new(&SOME_BUF); + let or_else = MockMakeWriter::new(&OR_ELSE_BUF); + + let return_some = AtomicBool::new(true); + let make_writer = move || { + if return_some.swap(false, Ordering::Relaxed) { + OptionalWriter::some(some.make_writer()) + } else { + OptionalWriter::none() + } + }; + let make_writer = make_writer.or_else(or_else); + let c = { + #[cfg(feature = "ansi")] + let f = Format::default().without_time().with_ansi(false); + #[cfg(not(feature = "ansi"))] + let f = Format::default().without_time(); + Subscriber::builder() + .event_format(f) + .with_writer(make_writer) + .with_max_level(Level::TRACE) + .finish() + }; + + let _s = tracing::subscriber::set_default(c); + info!("hello"); + info!("world"); + info!("goodbye"); + + has_lines(&SOME_BUF, &[(Level::INFO, "hello")]); + has_lines( + &OR_ELSE_BUF, + &[(Level::INFO, "world"), (Level::INFO, "goodbye")], + ); + } + + #[test] + fn combinators_or_else_chain() { + lazy_static! { + static ref INFO_BUF: Mutex> = Mutex::new(vec![]); + static ref DEBUG_BUF: Mutex> = Mutex::new(vec![]); + static ref WARN_BUF: Mutex> = Mutex::new(vec![]); + static ref ERR_BUF: Mutex> = Mutex::new(vec![]); + } + + let info = MockMakeWriter::new(&INFO_BUF); + let debug = MockMakeWriter::new(&DEBUG_BUF); + let warn = MockMakeWriter::new(&WARN_BUF); + let err = MockMakeWriter::new(&ERR_BUF); + + let make_writer = err.with_max_level(Level::ERROR).or_else( + warn.with_max_level(Level::WARN).or_else( + info.with_max_level(Level::INFO) + .or_else(debug.with_max_level(Level::DEBUG)), + ), + ); + + let c = { + #[cfg(feature = "ansi")] + let f = Format::default().without_time().with_ansi(false); + #[cfg(not(feature = "ansi"))] + let f = Format::default().without_time(); + Subscriber::builder() + .event_format(f) + .with_writer(make_writer) + .with_max_level(Level::TRACE) + .finish() + }; + + let _s = tracing::subscriber::set_default(c); + + trace!("trace"); + debug!("debug"); + info!("info"); + warn!("warn"); + error!("error"); + + println!("max level debug"); + has_lines(&DEBUG_BUF, &[(Level::DEBUG, "debug")]); + + println!("max level info"); + has_lines(&INFO_BUF, &[(Level::INFO, "info")]); + + println!("max level warn"); + has_lines(&WARN_BUF, &[(Level::WARN, "warn")]); + + println!("max level error"); + has_lines(&ERR_BUF, &[(Level::ERROR, "error")]); + } + + #[test] + fn combinators_and() { + lazy_static! { + static ref A_BUF: Mutex> = Mutex::new(vec![]); + static ref B_BUF: Mutex> = Mutex::new(vec![]); + } + + let a = MockMakeWriter::new(&A_BUF); + let b = MockMakeWriter::new(&B_BUF); + + let lines = &[(Level::INFO, "hello"), (Level::INFO, "world")]; + + let make_writer = a.and(b); + let c = { + #[cfg(feature = "ansi")] + let f = Format::default().without_time().with_ansi(false); + #[cfg(not(feature = "ansi"))] + let f = Format::default().without_time(); + Subscriber::builder() + .event_format(f) + .with_writer(make_writer) + .with_max_level(Level::TRACE) + .finish() + }; + + let _s = tracing::subscriber::set_default(c); + info!("hello"); + info!("world"); + + has_lines(&A_BUF, &lines[..]); + has_lines(&B_BUF, &lines[..]); + } } diff --git a/tracing-subscriber/src/layer.rs b/tracing-subscriber/src/layer.rs index 346d7890c8..c886ade9bc 100644 --- a/tracing-subscriber/src/layer.rs +++ b/tracing-subscriber/src/layer.rs @@ -90,7 +90,7 @@ use std::{any::TypeId, marker::PhantomData}; /// /// Multiple `Layer`s may be composed in the same manner: /// ```rust -/// # use tracing_subscriber::{Layer, SubscriberExt}; +/// # use tracing_subscriber::{Layer, layer::SubscriberExt}; /// # use tracing::Subscriber; /// pub struct MyOtherLayer { /// // ... diff --git a/tracing-subscriber/src/prelude.rs b/tracing-subscriber/src/prelude.rs index 0264c2d508..396825a6fb 100644 --- a/tracing-subscriber/src/prelude.rs +++ b/tracing-subscriber/src/prelude.rs @@ -12,3 +12,7 @@ pub use crate::layer::{ }; pub use crate::util::SubscriberInitExt as _; + +#[cfg(feature = "fmt")] +#[cfg_attr(docsrs, doc(cfg(feature = "fmt")))] +pub use crate::fmt::writer::MakeWriterExt as _;