0

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.

miqrc
  • 1,964
  • 2
  • 18
  • 24
  • 2
    Don't be discouraged by the downvotes, it is most likely because people think it's a too basic question for stackoverflow and would fall under [too little research effort before asking](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users). – Finomnis Apr 30 '23 at 15:29

1 Answers1

5

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();
kmdreko
  • 42,554
  • 6
  • 57
  • 106