Write a log to terminal using `tracing` crate for any value of `RUST_LOG`

Is there a macro in the tracing crate that I can use to mimic println!, i.e. tracing::foo!("bar") will always show bar in the console no matter the logging level?

I guess I am asking if there is a tracing::foo that always pass through the attached env filter.

Update 1: This filter_fn in tracing_subscriber::filter - Rust looks promising.

no, there's always a Level attached to an event. the whole point of using tracing is the events can be filtered. if you want println! behavior, just use println!. alternatively, you can change the target of the event to some special value and set your filter to always including that target.

1 Like

println! was a bad comparison. I have multiple layers attached and want to see bar written on all of them. Thanks for the target: span! and event! with target might just do the job.

you can do complicated filtering using custom fields, but target is simpler to use because you can write shorter filter expression. (alternatively, span has short syntax too). see documentation of EnvFilter for full syntax.

suppose your code looks like:

let _my_span = trace_span!("my_span").entered();
info!(target: "my_target", no_filter = true, "Hello, world!");

here's some example filter expressions:

rem use target is the simplest way
> env RUST_LOG="my_target=trace,warn" cargo run
rem ignore target, use span only
> env RUST_LOG="[my_span]=trace,warn" cargo run
rem ingore target and span, any event with a field named `no_filter` (value doesn't matter)
> env RUST_LOG="[{no_filter}]=trace,warn" cargo run

please note, make sure to properly escape the environment variable (because of the brackets and braces) according to your shell, I'm using cmd in the above example.

also note, the custom field syntax is normally matched against fields on Spans, but if you only specify a field name without an span name and the value, it will apply to Spans AND Events.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.