torrust_tracker/bootstrap/
logging.rs

1//! Setup for the application logging.
2//!
3//! It redirects the log info to the standard output with the log threshold
4//! defined in the configuration.
5//!
6//! - `Off`
7//! - `Error`
8//! - `Warn`
9//! - `Info`
10//! - `Debug`
11//! - `Trace`
12//!
13//! Refer to the [configuration crate documentation](https://docs.rs/torrust-tracker-configuration) to know how to change log settings.
14use std::sync::Once;
15
16use torrust_tracker_configuration::{Configuration, Threshold};
17use tracing::level_filters::LevelFilter;
18
19static INIT: Once = Once::new();
20
21/// It redirects the log info to the standard output with the log threshold
22/// defined in the configuration.
23pub fn setup(cfg: &Configuration) {
24    let tracing_level = map_to_tracing_level_filter(&cfg.logging.threshold);
25
26    if tracing_level == LevelFilter::OFF {
27        return;
28    }
29
30    INIT.call_once(|| {
31        tracing_stdout_init(tracing_level, &TraceStyle::Default);
32    });
33}
34
35fn map_to_tracing_level_filter(threshold: &Threshold) -> LevelFilter {
36    match threshold {
37        Threshold::Off => LevelFilter::OFF,
38        Threshold::Error => LevelFilter::ERROR,
39        Threshold::Warn => LevelFilter::WARN,
40        Threshold::Info => LevelFilter::INFO,
41        Threshold::Debug => LevelFilter::DEBUG,
42        Threshold::Trace => LevelFilter::TRACE,
43    }
44}
45
46fn tracing_stdout_init(filter: LevelFilter, style: &TraceStyle) {
47    let builder = tracing_subscriber::fmt().with_max_level(filter).with_ansi(true);
48
49    let () = match style {
50        TraceStyle::Default => builder.init(),
51        TraceStyle::Pretty(display_filename) => builder.pretty().with_file(*display_filename).init(),
52        TraceStyle::Compact => builder.compact().init(),
53        TraceStyle::Json => builder.json().init(),
54    };
55
56    tracing::info!("Logging initialized");
57}
58
59#[derive(Debug)]
60pub enum TraceStyle {
61    Default,
62    Pretty(bool),
63    Compact,
64    Json,
65}
66
67impl std::fmt::Display for TraceStyle {
68    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
69        let style = match self {
70            TraceStyle::Default => "Default Style",
71            TraceStyle::Pretty(path) => match path {
72                true => "Pretty Style with File Paths",
73                false => "Pretty Style without File Paths",
74            },
75            TraceStyle::Compact => "Compact Style",
76            TraceStyle::Json => "Json Format",
77        };
78
79        f.write_str(style)
80    }
81}