gpt4 book ai didi

rust - 为什么在使用非静态记录器之前不打印 lazy_static slog::Logger?

转载 作者:行者123 更新时间:2023-11-29 07:57:32 25 4
gpt4 key购买 nike

如果我取消注释 create_loglogLOG 都会打印在控制台上。没有它,什么也不会打印。这是怎么回事?

#[macro_use]
extern crate slog;
extern crate slog_term;
extern crate slog_async;
#[macro_use]
extern crate lazy_static;

use slog::Drain;

lazy_static! {
static ref LOG: slog::Logger = create_log();
}

fn create_log() -> slog::Logger {
let decorator = slog_term::TermDecorator::new().force_plain().build();
let drain = slog_term::CompactFormat::new(decorator).build().fuse();
let drain = slog_async::Async::new(drain).build().fuse();
slog::Logger::root(drain, o!())
}

fn main() {
info!(LOG, "LOG"); // NOT printed unless next line is uncommented

// let log = create_log(); // enables printing both log and LOG
// info!(log, "log");
}

最佳答案

通过使用 slog-async,you have opted into :

slog-async allows building Drains that offload processing to another thread. Typically serialization and IO operations can be slow enough that they could make logging hinder performance of the main code. Sending logging records to another thread is much faster (ballpark of 100ns).

您的代码注册一个日志事件,该事件将被发送到另一个线程,然后立即退出。后台线程没有时间实际记录。

但是,通过在程序结束时休眠,它“有效”:

std::thread::sleep_ms(1000);

为什么另一种情况有效?同样,我们 turn to the docs ,强调我的:

When using std::process::exit to terminate a process with an exit code it is imporant to notice that destructors will not be called. This matters for slog_async as it will prevents flushing of the async drain and discarding messages that are not yet written.

惰性静态中的项目 do not have their destructors run (他们什么时候会,如果它的目的是永远活着)。

当您从 main 函数构造另一个记录器时,它被分配在堆栈上并将被删除。这会导致先前的日志消息也被刷新。

关于rust - 为什么在使用非静态记录器之前不打印 lazy_static slog::Logger?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47342036/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com