How to transform a String into a Level to be used with tracing_subscriber?

I want to set the tracing Level using a String (because I get the Level from an env var).

let env_log_level = std::env::var("LOG_LEVEL").unwrap();

tracing_subscriber::fmt()
    .with_max_level(tracing::Level::DEBUG) // somehow use env_log_level here
    .with_target(false)
    .init();

I guess it should be a way to parse a String into a Level object but I don’t see how.

>Solution :

Level implements FromStr which accepts "error", "warn", "info", "debug", or "trace" (case-insensitive). So you can use that like so:

use std::str::FromStr;

let env_log_level = std::env::var("LOG_LEVEL").unwrap();

tracing_subscriber::fmt()
    .with_max_level(Level::from_str(&env_log_level).unwrap())
    .with_target(false)
    .init();

Note: I used ::from_str() instead of .parse() since .with_max_level() is generic and would need type annotations.


As suggested by @Finomnis, a more feature-rich solution would be to take advantage of EnvFilter since it allows configuring a global log level and much more (see docs).

tracing_subscriber::fmt()
    .with_env_filter(EnvFilter::from_env("LOG_LEVEL"))
    .with_target(false)
    .init();

Leave a Reply