Search code examples
loggingrustconcurrency

Is crate log at its simplest using its own thread for output?


Learning how you do logging in Rust.

env_logger::Builder::from_env(Env::default().default_filter_or("info"))
    .init();
info!("Logger initialised!");

With log and env_logger, are these messages logged "sync::mpsc::sync_channel" (multiple producer single consumer, preserving chronological order of submission), or not concurrent at all? This seems to suggest not, and the author there appears to be trying to "roll his own".

If not, what's the simplest route to using a concurrent logger in Rust? Obviously, I could set up my own sync_channel arrangement. Just wondering whether there are any "turnkey" solutions to this.

Maybe it doesn't matter: maybe the pipeline is lightweight enough that log output from multiple threads will always be printed in chronological order? At the moment I'm only logging to console, but I will want to find out how to log to files, and I can imagine that might be trickier.


Solution

  • The thing to understand is the log crate is simply a facade; it is just an interface between library crates that generate log messages and applications that direct and filter those messages however they prefer.

    So the log crate does not coordinate threads at all. A logging implementation will be initialized into some global resource and the log macros will forward all calls to it. It is the logging implementation that dictates any concurrency, threading, or ordering properties.

    In this case you're using the env-logger implementation. It is pretty straight-forward and boils down to a write call to stdout directly where the log macro was called. No channel, or separate thread, or additional synchronization beyond that.

    If you want different behavior so that the handling of logged messages doesn't slow down the code they are logged from, or your use-case is particularly sensitive to the timing and order, you'd have to use a different logging implementation that provides that kind of functionality.