tracing-appender does not write a single byte #1494
-
Bug ReportVersion
PlatformLinux jack-pc 5.10.53-1-MANJARO #1 SMP PREEMPT Mon Jul 26 07:18:28 UTC 2021 x86_64 GNU/Linux Cratestracing-appender v0.1.2 DescriptionOne way to structure the description: tracing-appender creates the specified log file, but does not write anything into it I tried this code: pub fn setup_logs(log_level: LevelFilter) -> anyhow::Result<()> {
// log_panics::init();
LogTracer::init().context("Cannot setup_logs")?;
let default_level = format!("[]={}", log_level);
let name = std::env::current_exe()?
.file_name()
.unwrap()
.to_str()
.unwrap()
.to_owned();
let appender = tracing_appender::rolling::hourly("logs", format!("{}.log", name));
let (non_blocking_appender, _guard) = tracing_appender::non_blocking(appender);
let subscriber = fmt()
.with_thread_names(true)
.with_writer(non_blocking_appender)
.with_env_filter(
&[
&default_level
]
.join(","),
)
.finish();
tracing::subscriber::set_global_default(subscriber).context("Cannot setup_logs")?;
Ok(())
} I expected to see this happen: the log file contains log |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
The However, in order for this to work, the returned guard value has to be held in the program's Try changing your code to something like this, and ensuring that you hold onto the returned guard in your pub fn setup_logs(log_level: LevelFilter) -> anyhow::Result<tracing_appender::non_blocking::WorkerGuard> {
// log_panics::init();
LogTracer::init().context("Cannot setup_logs")?;
let default_level = format!("[]={}", log_level);
let name = std::env::current_exe()?
.file_name()
.unwrap()
.to_str()
.unwrap()
.to_owned();
let appender = tracing_appender::rolling::hourly("logs", format!("{}.log", name));
let (non_blocking_appender, guard) = tracing_appender::non_blocking(appender);
let subscriber = fmt()
.with_thread_names(true)
.with_writer(non_blocking_appender)
.with_env_filter(
&[
&default_level
]
.join(","),
)
.finish();
tracing::subscriber::set_global_default(subscriber).context("Cannot setup_logs")?;
Ok(guard)
} |
Beta Was this translation helpful? Give feedback.
The
tracing_appender::non_blocking
function returns a non-blocking writer and a drop guard which flushes the writer and shuts it down when dropped. This is intended to be used to ensure the background thread terminates cleanly when the application exits, even in the event of a panic.However, in order for this to work, the returned guard value has to be held in the program's
main
function, since dropping it earlier will shut down the writer. In this case, yoursetup_logs
function drops the returned guard as soon as it exits, so the worker thread is shut down immediately.Try changing your code to something like this, and ensuring that you hold onto the returned guard in your
main
function:…