Skip to content

Commit 5671f34

Browse files
d-e-s-odavidbarsky
authored andcommitted
subscriber: enable TestWriter to write to stderr (#3187)
It can be useful to have a TestWriter that does not log to stdout but stderr instead. For example, that allows for potentially easier filtering of tracing output (because the remaining output of, say, cargo test goes to stdout) or to mirror behavior of env_logger, which by default logs to stderr. Introduce the TestWriter::with_stderr() constructor to enable such usage. The default is left unchanged. Co-authored-by: David Barsky <[email protected]>
1 parent da14f9b commit 5671f34

File tree

1 file changed

+19
-4
lines changed

1 file changed

+19
-4
lines changed

tracing-subscriber/src/fmt/writer.rs

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -494,8 +494,10 @@ pub trait MakeWriterExt<'a>: MakeWriter<'a> {
494494
///
495495
/// `TestWriter` is used by [`fmt::Subscriber`] or [`fmt::Layer`] to enable capturing support.
496496
///
497-
/// `cargo test` can only capture output from the standard library's [`print!`] macro. See
498-
/// [`libtest`'s output capturing][capturing] for more details about output capturing.
497+
/// `cargo test` can only capture output from the standard library's [`print!`] and [`eprint!`]
498+
/// macros. See [`libtest`'s output capturing][capturing] and
499+
/// [rust-lang/rust#90785](https://github.com/rust-lang/rust/issues/90785) for more details about
500+
/// output capturing.
499501
///
500502
/// Writing to [`io::stdout`] and [`io::stderr`] produces the same results as using
501503
/// [`libtest`'s `--nocapture` option][nocapture] which may make the results look unreadable.
@@ -509,7 +511,9 @@ pub trait MakeWriterExt<'a>: MakeWriter<'a> {
509511
/// [`print!`]: std::print!
510512
#[derive(Default, Debug)]
511513
pub struct TestWriter {
512-
_p: (),
514+
/// Whether or not to use `stderr` instead of the default `stdout` as
515+
/// the underlying stream to write to.
516+
use_stderr: bool,
513517
}
514518

515519
/// A writer that erases the specific [`io::Write`] and [`MakeWriter`] types being used.
@@ -708,12 +712,23 @@ impl TestWriter {
708712
pub fn new() -> Self {
709713
Self::default()
710714
}
715+
716+
/// Returns a new `TestWriter` that writes to `stderr` instead of `stdout`.
717+
pub fn with_stderr() -> Self {
718+
Self {
719+
use_stderr: true,
720+
}
721+
}
711722
}
712723

713724
impl io::Write for TestWriter {
714725
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
715726
let out_str = String::from_utf8_lossy(buf);
716-
print!("{}", out_str);
727+
if self.use_stderr {
728+
eprint!("{}", out_str)
729+
} else {
730+
print!("{}", out_str)
731+
}
717732
Ok(buf.len())
718733
}
719734

0 commit comments

Comments
 (0)