Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading