rust-lang / log

Logging implementation for Rust
https://docs.rs/log
Apache License 2.0
2.21k stars 256 forks source link

Custom log levels #636

Open koraa opened 4 months ago

koraa commented 4 months ago

Hi,

thank you all for writing a fantastic piece of software.

I am aware of https://github.com/rust-lang/log/issues/334.

My particular use case is having a log level "responsive" between warn and info.

https://github.com/rosenpass/rosenpass/pull/326

Our goal is to be:

Essentially be responsive without polluting logs.

Some ideas how to – cleanly – implement custom log levels:

KodrAus commented 3 months ago

Hi @koraa 👋

That’s an interesting design direction. I don’t think we’re likely to complicate level management in log; it’s intended to be a direct and straightforward library and using a fixed set of coarse grained levels lets us do things like compile-time filtering.

This is something you could possibly use the existing target field on log records for. They’re populated with the module name by default but can be set to anything through the macros. If you wanted, you could write your own wrapper over the log macros that set it to your custom level and still get very cheap filtering.

I think we could also benefit from potentially enhancing our Metadata type, which is used for filtering, by adding key-values to it so you can filter on those too.

koraa commented 3 months ago

Hi @KodrAus

thanks for the detailed response!

An elegant way to add Key/Value type data to your metadata type would be great; this could directly be used to implement sublevels.

A mechanism based on static or dynamic polymorphism instead of a hash map would be optimal to avoid heap allocations during logging. This would also help to globally identify keys. If arbitrary strings where used as keys, there is a danger to get keys from different crates mixed up.

Anyway, thanks for the hard work on this crate!

Thomasdezeeuw commented 3 months ago

An elegant way to add Key/Value type data to your metadata type would be great; this could directly be used to implement sublevels.

Take a look at the kv module documentation: https://docs.rs/log/latest/log/kv/index.html.

A mechanism based on static or dynamic polymorphism instead of a hash map would be optimal to avoid heap allocations during logging. This would also help to globally identify keys. If arbitrary strings where used as keys, there is a danger to get keys from different crates mixed up.

I've used special targets in my create to "add" additonal log levels. Some examples: