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
//! The logging level can be changed by the `RUST_LOG` environment variable just like
//! [`env_logger`].
//!
//! ## Example
//!
//! ```
//! use log::{trace, debug, info, warn, error};
//!
//! fil_logger::init();
//!
//! trace!("some tracing");
//! debug!("debug information");
//! info!("normal information");
//! warn!("a warning");
//! error!("error!");
//! ```
//!
//! The default output looks like this (with log level debug):
//!
//! ```text
//! 2019-11-11T21:04:25.685 DEBUG simple > debug information
//! 2019-11-11T21:04:25.685 INFO simple > normal information
//! 2019-11-11T21:04:25.685 WARN simple > a warning
//! 2019-11-11T21:04:25.685 ERROR simple > error!
//! ```
//!
//! It is also possible to log as JSON, which is more verbose and contains the filename and line
//! number as additional information. To enable it, set the environment variable
//! `GOLOG_LOG_FMT=json`:
//!
//! {"level":"debug","ts":"2019-11-11T21:06:45.401+0100","logger":"simple","caller":"examples/simple.rs:37",",sg":"debug information"}
//! {"level":"info","ts":"2019-11-11T21:06:45.401+0100","logger":"simple","caller":"examples/simple.rs:38","msg":"//! normal information"}
//! {"level":"warn","ts":"2019-11-11T21:06:45.401+0100","logger":"simple","caller":"examples/simple.rs:39","msg":"//! a warning"}
//! {"level":"error","ts":"2019-11-11T21:06:45.401+0100","logger":"simple","caller":"examples/simple.rs:40","msg":"error!"}
//!
//! [`env_logger`]: https://crates.io/crates/env_logger

#![deny(clippy::all, missing_docs)]

mod single_file_writer;

use std::{env, fs::File};

use flexi_logger::{self, style, DeferredNow, FormatFunction, Record};
use log::Level;
pub use single_file_writer::SingleFileWriter;

/// Logs in the same JSON format as [IPFS go-log] does.
///
/// One log entry has this structure:
///
/// ```json
/// {
///   "level": "<log-level>",
///   "ts":"<timestamp>",
///   "logger":"<module-name>",
///   "caller":"<source-file>:<line-number>",
///   "msg":"<log-message>"
/// }
/// ```
///
/// [IPFS go-log]: https://github.com/ipfs/go-log
pub fn go_log_json_format(
    writer: &mut dyn std::io::Write,
    now: &mut DeferredNow,
    record: &Record,
) -> Result<(), std::io::Error> {
    let level = match record.level() {
        Level::Error => "error",
        Level::Warn => "warn",
        Level::Info => "info",
        Level::Debug => "debug",
        Level::Trace => "trace",
    };
    write!(
        writer,
        r#"{{"level":"{}","ts":"{}","logger":"{}","caller":"{}:{}","msg":{:?}}}"#,
        level,
        now.now().format(GO_TIME_FORMAT),
        record.module_path().unwrap_or("<unnamed>"),
        record.file().unwrap_or("<unnamed>"),
        record.line().unwrap_or(0),
        &record.args().to_string()
    )
}

const GO_TIME_FORMAT: &str = "%Y-%m-%dT%H:%M:%S%.3f%z";
const DEFAULT_TIME_FORMAT: &str = "%Y-%m-%dT%H:%M:%S%.3f";

/// Logs with color, contains the same information as the [pretty_env_logger].
///
/// One log entry has this structure:
///
/// ```text
/// <timestamp> <log-level> <module-name> > <log-message>
/// ```
///
/// [pretty_env_logger]: https://crates.io/crates/pretty_env_logger
pub fn color_logger_format(
    writer: &mut dyn std::io::Write,
    now: &mut DeferredNow,
    record: &Record,
) -> Result<(), std::io::Error> {
    let level = record.level();
    write!(
        writer,
        "{} {} {} > {}",
        now.now().format(DEFAULT_TIME_FORMAT),
        style(level).paint(level.to_string()),
        record.module_path().unwrap_or("<unnamed>"),
        record.args(),
    )
}

/// Logs without color, contains the same information as the [pretty_env_logger].
///
/// One log entry has this structure:
///
/// ```text
/// <timestamp> <log-level> <module-name> > <log-message>
/// ```
///
/// [pretty_env_logger]: https://crates.io/crates/pretty_env_logger
pub fn nocolor_logger_format(
    writer: &mut dyn std::io::Write,
    now: &mut DeferredNow,
    record: &Record,
) -> Result<(), std::io::Error> {
    write!(
        writer,
        "{} {} {} > {}",
        now.format(DEFAULT_TIME_FORMAT),
        record.level(),
        record.module_path().unwrap_or("<unnamed>"),
        record.args(),
    )
}

/// Initializes a new logger. It logs to stderr.
///
/// The default format is:
///
/// ```text
/// <timestamp>\t<log-level>\t<module-name>\t<source-file>:<line-number>\t<log-message>
/// ```
///
/// If the environment variable `GOLOG_LOG_FMT=json` is set, then the output is formatted as JSON:
///
/// ```json
/// {
///   "level": "<log-level>",
///   "ts":"<timestamp>",
///   "logger":"<module-name>",
///   "caller":"<source-file>:<line-number>",
///   "msg":"<log-message>"
/// }
/// ```
///
/// # Panics
///
/// Panics if a global logger was already set or the value of `RUST_LOG` is malformed.
pub fn init() {
    flexi_logger::Logger::try_with_env()
        .expect("Invalid RUST_LOG")
        .format(log_format())
        .start()
        .expect("Initializing logger failed. Was another logger already initialized?");
}

/// Maybe initializes a new logger. It logs to stderr.
///
/// It will silently fail in case the logger cannot be initialized, e.g. due to some other logger
/// already running. This is useful for using it in tests, where it is more important that the
/// tests don't fail due to the logger, rather than having this specific logger initialized.
///
/// For more information about the log format, see [`init`].
///
/// # Panics
///
/// Panics if the value of `RUST_LOG` is malformed.
pub fn maybe_init() {
    let _ = flexi_logger::Logger::try_with_env()
        .expect("Invalid RUST_LOG")
        .format(log_format())
        .start();
}

/// initializes a new logger that logs to an already opened [`std::fs::File`].
///
/// For more information about the log format, see [`init`].
///
/// # Panics
///
/// Panics if a global logger was already set or the value of `RUST_LOG` is malformed.
///
/// [`std::fs::File`]: https://doc.rust-lang.org/std/fs/struct.File.html
pub fn init_with_file(file: File) {
    flexi_logger::Logger::try_with_env()
        .expect("Invalid RUST_LOG")
        .log_to_writer(Box::new(SingleFileWriter::new(file)))
        .format(log_format())
        .start()
        .expect("Initializing logger failed. Was another logger already initialized?");
}

/// The log format is based on the `GOLOG_LOG_FMT` environment variable. It can be set to `json`.
fn log_format() -> FormatFunction {
    match env::var("GOLOG_LOG_FMT") {
        Ok(ref format) if format == "json" => go_log_json_format,
        _ => {
            if atty::is(atty::Stream::Stderr) {
                color_logger_format
            } else {
                nocolor_logger_format
            }
        }
    }
}