Skip to content

Commit e66e6d9

Browse files
d-e-s-odavidbarsky
andauthored
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 c3f5745 commit e66e6d9

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
@@ -495,8 +495,10 @@ pub struct MutexGuardWriter<'a, W>(MutexGuard<'a, W>);
495495
///
496496
/// `TestWriter` is used by [`fmt::Collector`] or [`fmt::Subscriber`] to enable capturing support.
497497
///
498-
/// `cargo test` can only capture output from the standard library's [`print!`] macro. See
499-
/// [`libtest`'s output capturing][capturing] for more details about output capturing.
498+
/// `cargo test` can only capture output from the standard library's [`print!`] and [`eprint!`]
499+
/// macros. See [`libtest`'s output capturing][capturing] and
500+
/// [rust-lang/rust#90785](https://github.com/rust-lang/rust/issues/90785) for more details about
501+
/// output capturing.
500502
///
501503
/// Writing to [`io::stdout`] and [`io::stderr`] produces the same results as using
502504
/// [`libtest`'s `--nocapture` option][nocapture] which may make the results look unreadable.
@@ -510,7 +512,9 @@ pub struct MutexGuardWriter<'a, W>(MutexGuard<'a, W>);
510512
/// [`print!`]: std::print!
511513
#[derive(Default, Debug)]
512514
pub struct TestWriter {
513-
_p: (),
515+
/// Whether or not to use `stderr` instead of the default `stdout` as
516+
/// the underlying stream to write to.
517+
use_stderr: bool,
514518
}
515519

516520
/// A writer that erases the specific [`io::Write`] and [`MakeWriter`] types being used.
@@ -670,12 +674,23 @@ impl TestWriter {
670674
pub fn new() -> Self {
671675
Self::default()
672676
}
677+
678+
/// Returns a new `TestWriter` that writes to `stderr` instead of `stdout`.
679+
pub fn with_stderr() -> Self {
680+
Self {
681+
use_stderr: true,
682+
}
683+
}
673684
}
674685

675686
impl io::Write for TestWriter {
676687
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
677688
let out_str = String::from_utf8_lossy(buf);
678-
print!("{}", out_str);
689+
if self.use_stderr {
690+
eprint!("{}", out_str)
691+
} else {
692+
print!("{}", out_str)
693+
}
679694
Ok(buf.len())
680695
}
681696

0 commit comments

Comments
 (0)