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
//! A simple configurable logger with format specification.
//!
//! This crate provides an implementation of [`log` crate](https://docs.rs/log), which
//! provides integrated logging interface.
//!
//! ## Examples
//! #### Basic
//!
//! ```rust
//! #[macro_use]
//! extern crate log;
//! extern crate fmtlog;
//!
//! fn main() {
//!     fmtlog::default().set().unwrap();
//!
//!     info!("Hello!"); // INFO: Hello!
//! }
//! ```
//! See also [the function `default`](fn.default.html).
//!
//! #### Configure in Code
//!
//! ```rust
//! #[macro_use]
//! extern crate log;
//! extern crate fmtlog;
//!
//! use fmtlog::{Config, LevelFilter};
//!
//! fn main() {
//!     fmtlog::new(Config::new().level(LevelFilter::Trace))
//!         .set()
//!         .unwrap();
//!
//!     info!("Hello!"); // INFO: Hello!
//! }
//! ```
//! See also [the struct `Config`](struct.Config.html).
//!
//! ## Format Specification
//! The format string is basically a string, but the following specifiers will converted into
//! another string.
//!
//! | Spec. | Example | Description |
//! |-------|---------|-------------|
//! | `%%` | | Literal `%`. |
//! | `%}` | | Literal `}`. (use in `{}`.) |
//! | `%N` | `hyper` | The target of the log. |
//! | `%f` | `main.rs` | The file that the log defined. |
//! | `%S` | `main.rs:15` | The file and line that the log defined. |
//! | `%M` | `An error has occured.` | The log message. |
//! | `%l` | `info` | The log level. (lowercase) |
//! | `%L` | `INFO` | The log level. (uppercase) |
//! | `%T(<format>)` | `%T(%D %T)` -> `01/01/21 12:00:00` | The local time. (see [chrono's format specification](https://docs.rs/chrono/0.4/chrono/format/strftime)). **Requires feature: `chrono`** |
//! | `%U(<format>)` | `%T(%D %T)` -> `01/01/21 12:00:00` | The UTC time. (see [chrono's format specification](https://docs.rs/chrono/0.4/chrono/format/strftime)). **Requires feature: `chrono`** |
//! | `%F(<color>){...}` | | Set the foreground color. **Requires feature: `colored`** |
//! | `%F(<error>,<warn>,<info>,<debug>,<trace>){...}` | | Set the foreground color. (Branch by the log level.) **Requires feature: `colored`** |
//! | `%B(<color>){...}` | | Set the background color. **Requires feature: `colored`** |
//! | `%B(<error>,<warn>,<info>,<debug>,<trace>){...}` | | Set the background color. (Branch by the log level.) **Requires feature: `colored`** |
//! | `%b{...}` | | Bold the text. **Requires feature: `colored`** |
//! | `%d{...}` | | Dim the text color. **Requires feature: `colored`** |
//! | `%i{...}` | | Print the text in italics. **Requires feature: `colored`** |
//! | `%r{...}` | | Reverse the foreground and background color. **Requires feature: `colored`** |
//! | `%u{...}` | | Underline the text. **Requires feature: `colored`** |
//! | `%s{...}` | | Strikethrough the text. **Requires feature: `colored`** |
//!
//! ### Supported Color (Requires feature: `colored`)
//! All supported color used by `%C` and `%O` is here.
//! - `black`
//! - `red`
//! - `green`
//! - `yellow`
//! - `blue`
//! - `magenta` (= `purple`)
//! - `cyan`
//! - `white`
//! - `bright black`
//! - `bright red`
//! - `bright green`
//! - `bright yellow`
//! - `bright blue`
//! - `bright magenta`
//! - `bright cyan`
//! - `bright white`
//! - `#ffffff` (Hexadecimal RGB)
//!
extern crate log;
extern crate thread_local;

#[cfg(feature = "colored")]
extern crate colored;

pub mod formats;

mod config;
mod format;
mod module;
mod stream;

pub use config::*;

use format::Format;
use module::Modules;
use stream::Stream;

use log::{set_boxed_logger, set_max_level, Log, Metadata, Record, SetLoggerError};
use std::cell::RefCell;
use thread_local::ThreadLocal;

/// The body of fmtlog.
pub struct Logger {
    format: Format,
    level: log::LevelFilter,
    modules: Modules,
    // (Output, Colorize)
    streams: Vec<(Output, bool)>,
    // (Stream, Colorize)
    writer: ThreadLocal<RefCell<Vec<(Stream, bool)>>>,
}

impl Logger {
    /// Create a new instance.
    pub fn new(config: Config) -> Logger {
        let outputs = config.output;

        #[cfg(feature = "colored")]
        let streams = {
            let colorize = config.colorize;
            outputs
                .into_iter()
                .map(|o| (o.clone(), colorize.colorize(&o)))
                .collect()
        };

        #[cfg(not(feature = "colored"))]
        let streams = outputs.into_iter().map(|o| (o, false)).collect();

        Logger {
            format: Format::new(config.format).expect("Invalid Format."),
            level: config.level.into(),
            modules: Modules::from(config.modules),
            streams,
            writer: ThreadLocal::new(),
        }
    }

    /// Set this logger active.
    ///
    /// # Example
    ///
    /// ```rust
    /// #[macro_use]
    /// extern crate log;
    ///
    /// use fmtlog::{Logger, Config};
    ///
    /// fn main() {
    ///     Logger::new(Config::new()).set().unwrap();
    ///     info!("Hello!") // INFO: Hello!
    /// }
    /// ```
    pub fn set(self) -> Result<(), SetLoggerError> {
        set_max_level(self.level);
        set_boxed_logger(Box::new(self))
    }
}

impl Log for Logger {
    fn enabled(&self, metadata: &Metadata) -> bool {
        self.level >= metadata.level()
    }

    fn log(&self, record: &Record) {
        if !self.enabled(record.metadata()) {
            return;
        }

        if let Some(m) = record.module_path() {
            if !self.modules.contains(&m) {
                return;
            }
        }

        // Get a writer or create new writer.
        let mut writer = self
            .writer
            .get_or(|| {
                RefCell::new(
                    self.streams
                        .iter()
                        .map(|s| (s.0.to_stream().expect("Failed to open the file."), s.1))
                        .collect(),
                )
            })
            .borrow_mut();

        // Write to all writers.
        writer
            .iter_mut()
            .map(|w| self.format.write(&mut w.0, record, w.1))
            .collect::<Result<Vec<_>, _>>()
            .expect("Failed to write");
    }

    fn flush(&self) {
        use std::io::Write;

        match self.writer.get() {
            Some(writer) => {
                // Flush all writers.
                writer
                    .borrow_mut()
                    .iter_mut()
                    .map(|w| w.0.flush())
                    .collect::<Result<Vec<_>, _>>()
                    .expect("Failed to flush the stream.");
            }
            None => {}
        }
    }
}

/// Create a logger by default settings.
///
/// This function wraps [`Config::default`](struct.Config.html#impl-Default).
///
/// # Example
///
/// ```rust
/// #[macro_use]
/// extern crate log;
/// extern crate fmtlog;
///
/// fn main() {
///     fmtlog::default().set().unwrap();
///
///     info!("Hello!"); // INFO: Hello!
/// }
/// ```
pub fn default() -> Logger {
    Logger::new(Config::default())
}

/// Create a logger by custom settings.
///
/// This function wraps [`Logger::new`](struct.Logger.html#method.new).
///
/// # Example
///
/// ```rust
/// #[macro_use]
/// extern crate log;
/// extern crate fmtlog;
///
/// use fmtlog::Config;
///
/// fn main() {
///     fmtlog::new(Config::new()).set().unwrap();
///
///     info!("Hello!"); // INFO: Hello!
/// }
/// ```
pub fn new(config: Config) -> Logger {
    Logger::new(config)
}