tracing_appender
doesn't write the logs to its output immediately, but buffers them for some time. Therefore, this info
output is stored in the buffer, println
executes, main
returns, and program is terminated before the log gets printed.
To ensure that the logs will be flushed, you must use the returned guard
value. According to documentation, you're expected to store it in variable which is dropped after all the logs were sent - for example, at the end of main
; therefore, this will almost work:
use tracing::info;
fn main() {
let guard = init();
info!("test me");
println!("i should have info! message before this")
}
pub fn init() -> tracing_appender::non_blocking::WorkerGuard {
let (non_blocking, guard) = tracing_appender::non_blocking(std::io::stdout());
tracing_subscriber::fmt()
.with_writer(non_blocking)
.init();
guard
}
I say "almost", because it will still first execute println!
:
i should have info! message before this
2022-08-03T18:08:51.728620Z INFO playground: test me
It's not advised to mix tracing
logs and print
s in general, precisely because of the buffering. In this specific case, however, it's possible to get the result you want - just add drop(guard)
before println
.