Skip to main content


For writing simple formatted strings in #RustLang, I have these two macros in stdlib available: println!() to stdout or writeln!() to anything that implements the std::io::Write trait. The log crate only contains the equivalent macros to println!(), is there any option to have similar macros that behave like writeln!(), but for the log::Log trait? I know the macros in the log crate are quite involved, and I'd prefer to not ship my own set that simulates their behavior.
the option is to implement the trait for some type.
@matze Yes, that's what I did as a preliminary solution. The drawback with that is, that you loose all the nice functionality that the macros from the log crate give you, such as including file and line number information.
I don't understand what your problem is. If you implement the Log trait you keep using the macros but can decide what to do with the messages. Here's an example that wraps a writer: https://gist.github.com/rust-play/5c3f72db3658a2621473ecc3983b4ae7
@matze Ok, I misunderstood your proposal then. The issue is that I have some code that should log into a db when called from a job runner, and log to some other logger (e.g. simple_logger) in all other cases, but inside the same process. This appears impossible to me with the current implementation of the log crate. I wouldn't know how to differentiate that in the implementation of the log::Log trait.
sounds like an architectural problem rather than one with the log trait. But yes, the point of that trait is that you have one global logger instance and doing what you want to do would mean hacks or some different architecture.
It looks to me like the trait is just fine and provides everything that is needed. I'd just like to have a variant of the `log!(…)` and the `debug(…)`, `info(…)` etc. macros where I can pass in an explicit `log::Log` trait implementation in addition to the rest of the arguments. Just like it is possible with `writeln!(…)` in contrast to `println!(…)`.
This entry was edited (1 year ago)
@matze Did some investigation of the log crate, and it should be possible to mimic that, but only by using or mirroring functionality from that crate which is considered private (not technically, but by convention, doc hidden and some strong warning in a comment).
Hm, that'd be convenient on systems where you don't want to use an implicit global (internally mutable) logger but can pass one around explicitly. (Plus it'd allow monomorphization of logging).
@chrysn Exactly. The use case is that I implement a job runner system that must log the output into some database. Because parts the code should be shared with execution outside of the job runner, I'd like to pass in the logger.