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

subscriber: enable TestWriter to write to stderr #3187

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
21 changes: 17 additions & 4 deletions tracing-subscriber/src/fmt/writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -495,8 +495,8 @@ pub struct MutexGuardWriter<'a, W>(MutexGuard<'a, W>);
///
/// `TestWriter` is used by [`fmt::Collector`] or [`fmt::Subscriber`] to enable capturing support.
///
/// `cargo test` can only capture output from the standard library's [`print!`] macro. See
/// [`libtest`'s output capturing][capturing] for more details about output capturing.
/// `cargo test` can only capture output from the standard library's [`print!`] and [`eprint!`]
/// macros. See [`libtest`'s output capturing][capturing] for more details about output capturing.
///
/// Writing to [`io::stdout`] and [`io::stderr`] produces the same results as using
/// [`libtest`'s `--nocapture` option][nocapture] which may make the results look unreadable.
Expand All @@ -510,7 +510,9 @@ pub struct MutexGuardWriter<'a, W>(MutexGuard<'a, W>);
/// [`print!`]: std::print!
#[derive(Default, Debug)]
pub struct TestWriter {
_p: (),
/// Whether or not to use `stderr` instead of the default `stdout` as
/// the underlying stream to write to.
use_stderr: bool,
}

/// A writer that erases the specific [`io::Write`] and [`MakeWriter`] types being used.
Expand Down Expand Up @@ -670,12 +672,23 @@ impl TestWriter {
pub fn new() -> Self {
Self::default()
}

/// Returns a new `TestWriter` that writes to `stderr` instead of `stdout`.
pub fn with_stderr() -> Self {
Self {
use_stderr: true,
}
}
}

impl io::Write for TestWriter {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let out_str = String::from_utf8_lossy(buf);
print!("{}", out_str);
if self.use_stderr {
eprint!("{}", out_str)
} else {
print!("{}", out_str)
}
Ok(buf.len())
}

Expand Down
Loading