hickory_util/
lib.rs

1// Copyright 2015-2022 Benjamin Fry <benjaminfry@me.com>
2//
3// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4// https://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// https://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8use std::env;
9
10use tracing::metadata::LevelFilter;
11use tracing_subscriber::{EnvFilter, layer::SubscriberExt, util::SubscriberInitExt};
12
13fn get_env() -> String {
14    env::var("RUST_LOG").unwrap_or_default()
15}
16
17fn get_levels<T: ToString>(bin: &str, level: Option<T>) -> String {
18    let hickory_crates = level.map(|level| {
19        format!(
20            "{bin}={level},hickory_dns={level}",
21            bin = bin,
22            level = level.to_string().to_lowercase(),
23        )
24    });
25
26    if let Some(hickory_crates) = hickory_crates {
27        format!(
28            "{hickory_crates},{env}",
29            hickory_crates = hickory_crates,
30            env = get_env()
31        )
32    } else {
33        get_env()
34    }
35}
36
37/// Setup the logging for the given Level of output and all hickory-dns crates
38///
39/// # Panic
40///
41/// This will panic if the tracing subscriber can't be registered
42pub fn logger(bin: &str, level: Option<tracing::Level>) {
43    // Setup tracing for logging based on input
44    let subscriber = EnvFilter::builder()
45        .with_default_directive(LevelFilter::OFF.into())
46        .parse(get_levels(bin, level))
47        .expect("failed to configure tracing/logging");
48
49    let formatter = tracing_subscriber::fmt::layer().compact();
50
51    tracing_subscriber::registry()
52        .with(formatter)
53        .with(subscriber)
54        .init();
55}