Skip to main content

tari_common/
logging.rs

1// Copyright 2019. The Tari Project
2//
3// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
4// following conditions are met:
5//
6// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
7// disclaimer.
8//
9// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
10// following disclaimer in the documentation and/or other materials provided with the distribution.
11//
12// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
13// products derived from this software without specific prior written permission.
14//
15// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
16// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
17// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
18// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
19// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
20// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
21// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
22//
23
24use std::{
25    fs,
26    fs::File,
27    io::{Read, Write},
28    path::Path,
29};
30
31use log4rs::config::RawConfig;
32
33use crate::ConfigError;
34
35/// Set up application-level logging using the Log4rs configuration file specified in
36pub fn initialize_logging(config_file: &Path, base_path: &Path, default: &str) -> Result<(), ConfigError> {
37    println!(
38        "Initializing logging according to {:?}",
39        config_file.to_str().unwrap_or("[??]")
40    );
41
42    if !config_file.exists() {
43        if let Some(d) = config_file.parent() {
44            fs::create_dir_all(d)
45                .map_err(|e| ConfigError::new("Could not create parent directory for log file", Some(e.to_string())))?
46        };
47        let mut file = File::create(config_file)
48            .map_err(|e| ConfigError::new("Could not create default log file", Some(e.to_string())))?;
49        file.write_all(default.as_ref())
50            .map_err(|e| ConfigError::new("Could not create default log file", Some(e.to_string())))?;
51    }
52
53    let mut file =
54        File::open(config_file).map_err(|e| ConfigError::new("Could not locate file: {}", Some(e.to_string())))?;
55    let mut contents = String::new();
56
57    file.read_to_string(&mut contents)
58        .map_err(|e| ConfigError::new("Could not read file: {}", Some(e.to_string())))?;
59
60    let replace_str = base_path
61        .to_str()
62        .expect("Could not replace {{log_dir}} variable from the log4rs config")
63        // log4rs requires the path to be in a unix format regardless of the system it's running on
64        .replace('\\', "/");
65
66    let contents = contents.replace("{{log_dir}}", &replace_str);
67
68    let config: RawConfig =
69        serde_yaml::from_str(&contents).expect("Could not parse the contents of the log file as yaml");
70    log4rs::init_raw_config(config).expect("Could not initialize logging");
71
72    Ok(())
73}
74
75/// Log an error if an `Err` is returned from the `$expr`. If the given expression is `Ok(v)`,
76/// `Some(v)` is returned, otherwise `None` is returned (same as `Result::ok`).
77/// Useful in cases where the error should be logged and ignored.
78/// instead of writing `if let Err(err) = my_error_call() { error!(...) }`, you can write
79/// `log_if_error!(my_error_call())`
80///
81/// ```edition2018
82/// # use tari_common::log_if_error;
83/// let opt = log_if_error!(level: debug, target: "docs", "Error sending reply: {}", Result::<(), _>::Err("this will be logged"));
84/// assert_eq!(opt, None);
85/// ```
86#[macro_export]
87macro_rules! log_if_error {
88    (level:$level:tt, target: $target:expr, $msg:expr, $expr:expr $(,)*) => {{
89        match $expr {
90            Ok(v) => Some(v),
91            Err(err) => {
92                log::$level!(target: $target, $msg, err);
93                None
94            }
95        }
96    }};
97    (level:$level:tt, $msg:expr, $expr:expr $(,)*) => {{
98        log_if_error!(level:$level, target: "$crate", $msg, $expr)
99    }};
100     (target: $target:expr, $msg:expr, $expr:expr $(,)*) => {{
101        log_if_error!(level:warn, target: $target, $msg, $expr)
102    }};
103    ($msg:expr, $expr:expr $(,)*) => {{
104        log_if_error!(level:warn, target: "$crate", $msg, $expr)
105    }};
106}
107
108/// See [log_if_error!](./log_if_error.macro.html).
109///
110/// ```edition2018
111/// # use tari_common::log_if_error_fmt;
112/// let opt = log_if_error_fmt!(level: debug, target: "docs", "Error sending reply - custom: {}", Result::<(), _>::Err(()), "this is logged");
113/// assert_eq!(opt, None);
114/// ```
115#[macro_export]
116macro_rules! log_if_error_fmt {
117    (level: $level:tt, target: $target:expr, $msg:expr, $expr:expr, $($args:tt)+) => {{
118        match $expr {
119            Ok(v) => Some(v),
120            Err(_) => {
121                log::$level!(target: $target, $msg, $($args)+);
122                None
123            }
124        }
125    }};
126}
127
128#[cfg(test)]
129mod test {
130    #[test]
131    fn log_if_error() {
132        let err = Result::<(), _>::Err("What a shame");
133        let opt = log_if_error!("Error: {}", err);
134        assert!(opt.is_none());
135
136        let opt = log_if_error!(level: trace, "Error: {}", err);
137        assert!(opt.is_none());
138
139        let opt = log_if_error!(level: trace, "Error: {}", Result::<_, &str>::Ok("answer"));
140        assert_eq!(opt, Some("answer"));
141    }
142}