1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
//! Configuration of the logger.

use std::env;
use std::marker::PhantomData;

use log::{kv, LevelFilter, SetLoggerError};

use crate::format::{Format, Gcloud, Json, LogFmt};
#[cfg(feature = "log-panic")]
use crate::PANIC_TARGET;
use crate::{Logger, Targets};

/// Configuration of the logger.
///
/// It support three logging formats:
///  * [`logfmt`](Config::logfmt) and
///  * [`json`](Config::json) and
///  * [`gcloud`](Config::gcloud).
#[derive(Debug)]
pub struct Config<F, Kvs> {
    filter: LevelFilter,
    add_loc: Option<bool>,
    targets: Targets,
    kvs: Kvs,
    _format: PhantomData<F>,
}

impl Config<(), NoKvs> {
    /// Logfmt following <https://www.brandur.org/logfmt>.
    pub fn logfmt() -> Config<LogFmt, NoKvs> {
        Config::new(NoKvs)
    }

    /// Structured logging using JSON.
    pub fn json() -> Config<Json, NoKvs> {
        Config::new(NoKvs)
    }

    /// Google Cloud Platform structured logging using JSON, following
    /// <https://cloud.google.com/logging/docs/structured-logging>.
    pub fn gcloud() -> Config<Gcloud, NoKvs> {
        Config::new(NoKvs)
    }
}

impl<F, Kvs> Config<F, Kvs>
where
    F: Format + Send + Sync + 'static,
    Kvs: kv::Source + Send + Sync + 'static,
{
    fn new(kvs: Kvs) -> Config<F, Kvs> {
        Config {
            filter: get_max_level(),
            add_loc: None,
            targets: get_log_targets(),
            kvs,
            _format: PhantomData,
        }
    }

    /// Add the key-values `kvs` to all logged messages.
    pub fn with_kvs<K>(self, kvs: K) -> Config<F, K>
    where
        K: kv::Source + Send + Sync + 'static,
    {
        Config {
            filter: self.filter,
            add_loc: self.add_loc,
            targets: self.targets,
            kvs,
            _format: self._format,
        }
    }

    /// Enable or disable logging of the call location.
    ///
    /// Default to enable if the debug (or lower) messages are enabled.
    pub fn with_call_location(self, enable: bool) -> Config<F, Kvs> {
        Config {
            filter: self.filter,
            add_loc: Some(enable),
            targets: self.targets,
            kvs: self.kvs,
            _format: self._format,
        }
    }

    /// Initialise the logger.
    ///
    /// See the [crate level documentation] for more.
    ///
    /// [crate level documentation]: index.html
    ///
    /// # Panics
    ///
    /// This will panic if the logger fails to initialise. Use [`Config::try_init`] if
    /// you want to handle the error yourself.
    pub fn init(self) {
        self.try_init()
            .unwrap_or_else(|err| panic!("failed to initialise the logger: {err}"));
    }

    /// Try to initialise the logger.
    ///
    /// Unlike [`Config::init`] this doesn't panic when the logger fails to initialise.
    /// See the [crate level documentation] for more.
    ///
    /// [`init`]: fn.init.html
    /// [crate level documentation]: index.html
    pub fn try_init(self) -> Result<(), SetLoggerError> {
        let logger = Box::new(Logger {
            filter: self.filter,
            add_loc: self.add_loc.unwrap_or(self.filter >= LevelFilter::Debug),
            targets: self.targets,
            kvs: self.kvs,
            _format: self._format,
        });
        log::set_boxed_logger(logger)?;
        log::set_max_level(self.filter);

        #[cfg(feature = "log-panic")]
        std::panic::set_hook(Box::new(log_panic));
        Ok(())
    }
}

/// Get the maximum log level based on the environment.
pub(crate) fn get_max_level() -> LevelFilter {
    for var in &["LOG", "LOG_LEVEL"] {
        if let Ok(level) = env::var(var) {
            if let Ok(level) = level.parse() {
                return level;
            }
        }
    }

    if env::var("TRACE").is_ok() {
        LevelFilter::Trace
    } else if env::var("DEBUG").is_ok() {
        LevelFilter::Debug
    } else {
        LevelFilter::Info
    }
}

/// Get the targets to log, if any.
pub(crate) fn get_log_targets() -> Targets {
    match env::var("LOG_TARGET") {
        Ok(ref targets) if !targets.is_empty() => {
            Targets::Only(targets.split(',').map(Into::into).collect())
        }
        _ => Targets::All,
    }
}

/// Panic hook that logs the panic using [`log::error!`].
#[cfg(feature = "log-panic")]
fn log_panic(info: &std::panic::PanicInfo<'_>) {
    use std::backtrace::Backtrace;
    use std::thread;

    let thread = thread::current();
    let thread_name = thread.name().unwrap_or("unnamed");
    let (file, line) = match info.location() {
        Some(location) => (location.file(), location.line()),
        None => ("<unknown>", 0),
    };
    let backtrace = Backtrace::force_capture();

    log::logger().log(
        &log::Record::builder()
            // Format for {info}: "panicked at '$message', $file:$line:$col".
            .args(format_args!("thread '{thread_name}' {info}"))
            .level(log::Level::Error)
            .target(PANIC_TARGET)
            .file(Some(file))
            .line(Some(line))
            .key_values(&("backtrace", &backtrace as &dyn std::fmt::Display))
            .build(),
    );
}

/// No initial key-values.
#[derive(Debug)]
pub struct NoKvs;

impl kv::Source for NoKvs {
    fn visit<'kvs>(&'kvs self, _: &mut dyn log::kv::Visitor<'kvs>) -> Result<(), log::kv::Error> {
        Ok(())
    }

    fn get<'v>(&'v self, _: log::kv::Key<'_>) -> Option<log::kv::Value<'v>> {
        None
    }

    fn count(&self) -> usize {
        0
    }
}