fmt::Subscriber's output is not captured by cargo test #2406
-
fmt::Subscriber can output to Stdout and Stderr but this output is not captured by fn fn_print_and_log() {
println!("print1");
tracing::info!("trace1");
println!("print2");
tracing::info!("trace2");
}
#[test]
fn test1() {
tracing_subscriber::fmt::fmt().init();
fn_print_and_log();
}
This happens because output written directly to A stable but ugly solution I came up with is: struct S;
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for S {
type Writer = W;
fn make_writer(&'a self) -> Self::Writer {
W
}
}
struct W;
impl std::io::Write for W {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
// assume fmt::Subscriber only writes utf8 strings
let string = std::str::from_utf8(buf).unwrap();
print!("{}", string);
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
// `print!` already flushes
Ok(())
}
}
#[test]
fn test2() {
tracing_subscriber::fmt::fmt().with_writer(S).init();
fn_print_and_log();
} It is ugly because fmt::Subscriber only outputs strings which we convert to bytes for Write, convert back to strings to use I would like this to be fixed in fmt::Subscriber but this this solution feels ugly enough that it shouldn't be used. If someone had an idea for a better solution I would be open to making a PR with it. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Sorry for the delay in responding. This is already handled by https://docs.rs/tracing-subscriber/latest/tracing_subscriber/fmt/struct.Layer.html#method.with_test_writer. |
Beta Was this translation helpful? Give feedback.
Sorry for the delay in responding. This is already handled by https://docs.rs/tracing-subscriber/latest/tracing_subscriber/fmt/struct.Layer.html#method.with_test_writer.