~matthiasbeyer/imag

ref: be50f5ad51d05dd3d24ecfd6343055737a2757f0 imag/lib/core/libimagrt/src/logger.rs -rw-r--r-- 8.9 KiB
be50f5adMatthias Beyer builds: nixos: Switch to latest stable channel 1 year, 3 months ago
                                                                                                    
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//

use std::io::Write;
use std::io::stderr;
use std::collections::BTreeMap;
use std::sync::Arc;
use std::sync::Mutex;
use std::ops::Deref;

use anyhow::Result;
use anyhow::Error;

use clap::ArgMatches;
use log::{Log, Level, Record, Metadata};
use toml::Value;
use toml_query::read::TomlValueReadExt;
use toml_query::read::TomlValueReadTypeExt;
use handlebars::Handlebars;

#[derive(Debug)]
enum LogDestination {
    Stderr,
    File(Arc<Mutex<::std::fs::File>>),
}

impl Default for LogDestination {
    fn default() -> LogDestination {
        LogDestination::Stderr
    }
}

/// Logger implementation for `log` crate.
#[derive(Debug)]
pub struct ImagLogger {
    global_loglevel     : Level,

    #[allow(unused)]
    global_destinations : Vec<LogDestination>,

    handlebars: Handlebars,
}

impl ImagLogger {

    /// Create a new ImagLogger object with a certain level
    pub fn new(matches: &ArgMatches, config: Option<&Value>) -> Result<ImagLogger> {
        let mut handlebars = Handlebars::new();

        handlebars.register_escape_fn(::handlebars::no_escape);

        ::libimaginteraction::format::register_all_color_helpers(&mut handlebars);
        ::libimaginteraction::format::register_all_format_helpers(&mut handlebars);

        {
            use self::log_lvl_aggregate::*;
            aggregate::<Trace>(&mut handlebars, config, "TRACE")?;
            aggregate::<Debug>(&mut handlebars, config, "DEBUG")?;
            aggregate::<Info>(&mut handlebars, config, "INFO")?;
            aggregate::<Warn>(&mut handlebars, config, "WARN")?;
            aggregate::<Error>(&mut handlebars, config, "ERROR")?;
        }

        Ok(ImagLogger {
            global_loglevel     : aggregate_global_loglevel(matches, config)?,
            global_destinations : aggregate_global_destinations(config)?,
            handlebars,
        })
    }

    pub fn global_loglevel(&self) -> Level {
        self.global_loglevel
    }

}

impl Log for ImagLogger {

    fn enabled(&self, metadata: &Metadata) -> bool {
        metadata.level() <= self.global_loglevel
    }

    fn flush(&self) {
        // nothing?
    }

    fn log(&self, record: &Record) {
        let mut data = BTreeMap::new();

        {
            data.insert("level",        format!("{}", record.level()));
            data.insert("module_path",  String::from(record.module_path().unwrap_or("<modulepath unknown>")));
            data.insert("file",         String::from(record.file().unwrap_or("<file unknown>")));
            data.insert("line",         format!("{}", record.line().unwrap_or(0)));
            data.insert("target",       String::from(record.target()));
            data.insert("message",      format!("{}", record.args()));
        }

        let logtext = self
            .handlebars
            .render(&format!("{}", record.level()), &data)
            .unwrap_or_else(|e| format!("Failed rendering logging data: {:?}\n", e));

        let log_to_destination = |d: &LogDestination| match *d {
            LogDestination::Stderr => {
                let _ = writeln!(stderr(), "{}", logtext);
            },
            LogDestination::File(ref arc_mutex_logdest) => {
                // if there is an error in the lock, we cannot do anything. So we ignore it here.
                let _lock = arc_mutex_logdest
                    .deref()
                    .lock()
                    .map(|mut logdest| {
                        writeln!(logdest, "{}", logtext)
                    });
            }
        };

        if self.global_loglevel >= record.level() {
            // Yes, we log
            for d in self.global_destinations.iter() {
                // If there's an error, we cannot do anything, can we?
                log_to_destination(&d);
            }
        }
    }
}

fn match_log_level_str(s: &str) -> Result<Level> {
    match s {
        "trace" => Ok(Level::Trace),
        "debug" => Ok(Level::Debug),
        "info"  => Ok(Level::Info),
        "warn"  => Ok(Level::Warn),
        "error" => Ok(Level::Error),
        lvl     => Err(anyhow!("Invalid logging level: {}", lvl)),
    }
}

fn aggregate_global_loglevel(matches: &ArgMatches, config: Option<&Value>) -> Result<Level>
{
    fn get_arg_loglevel(matches: &ArgMatches) -> Result<Option<Level>> {
        if matches.is_present("debugging") {
            return Ok(Some(Level::Debug))
        }

        match matches.value_of("verbosity") {
            Some(v) => match_log_level_str(v).map(Some),
            None    => if matches.is_present("verbosity") {
                Ok(Some(Level::Info))
            } else {
                Ok(None)
            },
        }
    }

    if let Some(cfg) = config {
        let cfg_loglevel = cfg
            .read_string("imag.logging.level")?
            .ok_or_else(|| anyhow!("Global log level config missing"))
            .and_then(|s| match_log_level_str(&s))?;

        if let Some(cli_loglevel) = get_arg_loglevel(matches)? {
            if cli_loglevel > cfg_loglevel {
                return Ok(cli_loglevel)
            }
        }

        Ok(cfg_loglevel)

    } else {
        get_arg_loglevel(matches).map(|o| o.unwrap_or(Level::Info))
    }
}

fn translate_destination(raw: &str) -> Result<LogDestination> {
    use std::fs::OpenOptions;

    match raw {
        "-" => Ok(LogDestination::Stderr),
        other => {
            OpenOptions::new()
                .append(true)
                .create(true)
                .open(other)
                .map(Mutex::new)
                .map(Arc::new)
                .map(LogDestination::File)
                .map_err(Error::from)
        }
    }
}

fn aggregate_global_destinations(config: Option<&Value>) -> Result<Vec<LogDestination>> {
    match config {
        None      => Ok(vec![LogDestination::default()]),
        Some(cfg) => cfg
            .read("imag.logging.destinations")?
            .ok_or_else(|| anyhow!("Global log destination config missing"))?
            .as_array()
            .ok_or_else(|| {
                let msg = "Type error at 'imag.logging.destinations', expected 'Array'";
                anyhow!(msg)
            })
            .and_then(|raw| {
                raw.iter()
                    .map(|val| {
                        val.as_str()
                            .ok_or_else(|| anyhow!("Type error at 'imag.logging.modules.<mod>.destinations', expected Array<String>"))
                            .map_err(Error::from)
                            .and_then(|s| translate_destination(s))
                    })
                    .collect::<Result<Vec<LogDestination>>>()
            }),
    }
}

mod log_lvl_aggregate {
    use anyhow::Result;
    use anyhow::Error as E;
    use anyhow::Context;
    use toml::Value;
    use toml_query::read::TomlValueReadTypeExt;
    use handlebars::Handlebars;

    macro_rules! aggregate_global_format_with {
        ($t:ident, $read_str:expr) => {
            pub struct $t;
            impl LogLevelAggregator for $t {
                fn aggregate(config: Option<&Value>) -> Result<String> {
                    config.ok_or_else(|| {
                        E::from(anyhow!(concat!("Config missing: Logging format: ", stringify!($t))))
                    })?
                    .read_string($read_str)?
                    .ok_or_else(|| {
                        E::from(anyhow!(concat!("Config missing: Logging format: ", stringify!($t))))
                    })
                }
            }
        };
    }

    pub trait LogLevelAggregator {
        fn aggregate(config: Option<&Value>) -> Result<String>;
    }

    pub fn aggregate<T: LogLevelAggregator>(hb: &mut Handlebars, config: Option<&Value>, lvlstr: &str)
        -> Result<()>
    {
        hb.register_template_string(lvlstr, T::aggregate(config)?)
            .map_err(E::from)
            .context(anyhow!("Handlebars template error"))
            .map_err(E::from)
    }

    aggregate_global_format_with!(Trace, "imag.logging.format.trace");
    aggregate_global_format_with!(Debug, "imag.logging.format.debug");
    aggregate_global_format_with!(Info, "imag.logging.format.info");
    aggregate_global_format_with!(Warn, "imag.logging.format.warn");
    aggregate_global_format_with!(Error, "imag.logging.format.error");

}