Slog logger in multi threaded environment

hey guys, what's the best practice for sharing a logger among multiple threads. I'm thinking of making a static logger and exposing a method which returns a reference to it. does this make sense?
something like this, but i need to deal with lifetimes, this doesnt compile

pub static mut STATIC_LOGGER: Option<Logger> = None;

pub fn generate_logger() ->   Option<&Logger> {

    match STATIC_LOGGER{
        None => {
            let my_writer = MyWriter {};
            let decorator = slog_term::PlainSyncDecorator::new(io::stdout());
            let drain = slog_term::FullFormat::new(decorator).build().fuse();
            let async_and_text = slog_async::Async::new(drain).build().fuse();

            let json = slog_json::Json::default(my_writer).fuse();
            let async_and_json = slog_async::Async::new(json).build().fuse();

            let log = slog::Logger::root(slog::Duplicate::new(async_and_text, async_and_json).fuse(), o!("version" => env!("CARGO_PKG_VERSION")));
            STATIC_LOGGER = Some(log);
        }
        _ => {}
    }
    &STATIC_LOGGER
}


Consider using lazy_static to initialize the logger - you won’t need the Option then. The code you have currently is also racy and won’t compile for that reason either (without unsafe).

1 Like