Rust tracing basic setup
March 29, 2025 [Programming, Programming Languages, Rust, Tech]I spent ages yesterday trying to figure out how to use Rust's tracing library (and tracing-subscriber) for a very simple logging use-case.
I wanted to use tracing
because a) it's rapidly becoming standard everywhere
and b) I was using libraries that used it.
I found it very hard to find a simple example that either takes its log level
from the RUST_LOG
environment variable, or uses a non-trivial default. Here's
what I came up with:
$ cargo add tracing
$ cargo add tracing-subscriber --features env-filter
use tracing_subscriber::FmtSubscriber;
fn main() {
const DEFAULT_LOGGING: &str = "myprogram=info,warn";
let rust_log = std::env::var("RUST_LOG")
.ok()
.and_then(|s| if s.is_empty() { None } else { Some(s) })
.unwrap_or_else(|| DEFAULT_LOGGING.to_owned());
tracing::subscriber::set_global_default(
FmtSubscriber::builder().with_env_filter(rust_log).finish(),
)
.expect("tracing setup failed");
// The rest of my program here ...
}
The myprogram=info,warn
part sets the log level of my project to info
and
any libraries I use to warn
. You'll need to replace myprogram
with the name
of your project.
This sets a default logging level which can be overridden by launching the
program with e.g. RUST_LOG=debug ./myprogram
to set the level to debug
everywhere or e.g. RUST_LOG="myproject=debug,warn" ./myprogram
to do something
more clever.
(The format of these comma-separated lists of directives are kind of documented at tracing_fmt::Builder::with_env_filter and EnvFilter.)
Once that's done I can log using code like this:
use tracing::{debug, info};
pub fn myfun() {
let x = 3;
info!("The number is {x}");
debug!("DEBUG ONLY");
}
If anyone knows a simpler way to achieve these results, let me know. I spent a
long time fiddling with EnvFilter::with_default_directive
and similar stuff
before I decided I had to check the contents of RUST_LOG
manually if I wanted
a more complex default (not a single directive).
Side note: wow, tracing_subscriber
is hard to use! I couldn't find any simple
examples - links welcome.