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
#![deny(missing_docs)]
#![doc(html_root_url = "https://dabo.guru/rust/fern/")]
//! Efficient, configurable logging in rust
//!
//! With Fern, you can:
//!
//! - Configure logging at runtime; make changes based off of user arguments or configuration
//! - Format log records without allocating intermediate results
//! - Output to stdout, stderr, log files and custom destinations
//! - Apply a blanket level filter and per-crate/per-module overrides
//! - Intuitively apply filters and formats to groups of loggers via builder chaining
//! - Log using the standard `log` crate macros
//!
//! Fern, while feature-complete, does not have a mature API. The library may be changed
//! in backwards incompatible ways to make it more ergonomic in the future.
//!
//! # Depending on Fern
//!
//! To use fern effectively, depend on the `fern` and `log` crates in your project's `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! log = "0.3"
//! fern = "0.4"
//! ```
//!
//! Then declare both in your program's `main.rs` or `lib.rs`:
//!
//! ```
//! #[macro_use]
//! extern crate log;
//! extern crate fern;
//! # fn main() {}
//! ```
//!
//! # Example usage:
//!
//! In fern 0.4, creating, configuring, and establishing a logger as the global logger are all merged
//! into builder methods on the `Dispatch` struct.
//!
//! Here's an example logger which formats messages, limits to Debug level, and puts everything into both stdout and
//! an output.log file.
//!
//! ```no_run
//! # extern crate fern;
//! # #[macro_use]
//! # extern crate log;
//! extern crate chrono;
//!
//! # fn setup_logger() -> Result<(), fern::InitError> {
//! fern::Dispatch::new()
//!     .format(|out, message, record| {
//!         out.finish(format_args!("{}[{}][{}] {}",
//!             chrono::Local::now()
//!                 .format("[%Y-%m-%d][%H:%M:%S]"),
//!             record.target(),
//!             record.level(),
//!             message))
//!     })
//!     .level(log::LogLevelFilter::Debug)
//!     .chain(std::io::stdout())
//!     .chain(fern::log_file("output.log")?)
//!     .apply()?;
//! # Ok(())
//! # }
//! # fn main() { setup_logger().expect("failed to set up logger") }
//! ```
//!
//! Let's unwrap the above example:
//!
//! ---
//!
//! [`fern::Dispatch::new()`]
//!
//! Create an empty logger config.
//!
//! ---
//!
//! [`.format(|...| ...)`]
//!
//! Add a formatter to the logger, modifying all messages sent through.
//!
//! ___
//!
//! [`chrono::Local::now()`]
//!
//! Get the current time in the local timezone using the [`chrono`] library. See the [time-and-date docs].
//!
//! ___
//!
//! [`.format(`]`"[%Y-%m-%d][%H:%M:%S]`[`")`]
//!
//! Use chrono's lazy format specifier to turn the time into a readable string.
//!
//! ---
//!
//! [`out.finish(format_args!(...))`]
//!
//! Call the `fern::FormattingCallback` to submit the formatted message.
//!
//! Fern uses this callback style to allow usage of [`std::fmt`] formatting without the allocation that would
//! be needed to return the formatted result.
//!
//! [`format_args!()`] has the same arguments as [`println!()`] or any other [`std::fmt`]-based macro.
//!
//! The final output of this formatter will be:
//!
//! ```text
//! [2017-01-20][12:55:04][crate-name][INFO] Something happened.
//! ```
//!
//! ---
//!
//! [`.level(log::LogLevelFilter::Debug)`]
//!
//! Set the minimum level needed to output to Debug, accepting Debug, Info, Warn, and Error-level messages
//! and denying Trace-level messages.
//!
//! ---
//!
//! [`.chain(std::io::stdout())`]
//!
//! Add a child to the logger; send all messages to stdout.
//!
//! [`Dispatch::chain`] accepts Stdout, Stderr, Files and other Dispatch instances.
//!
//! ---
//!
//! [`.chain(fern::log_file(...)?)`]
//!
//! Add a second child; send all messages to the file "output.log".
//!
//! See [`fern::log_file()`] for more info on file output.
//!
//! ---
//!
//! [`.apply()`][`.apply`]
//!
//! Consume the configuration and instantiate it as the current runtime global logger.
//!
//! This will fail if and only if another fern or [`log`] logger has already been set as the global logger.
//!
//! Since it's really up to the binary-producing crate to set up logging, the [`apply`] result can be reasonably
//! unwrapped.
//!
//! # Logging
//!
//! Once the logger has been set using [`apply`] it will pick up all [`log`] macro calls from your
//! crate and all your libraries.
//!
//! ```rust
//! #[macro_use]
//! extern crate log;
//! extern crate fern;
//!
//! # fn setup_logger() -> Result<(), fern::InitError> {
//! fern::Dispatch::new()
//!     // ...
//!     .apply()?;
//! # Ok(())
//! # }
//!
//! # fn main() {
//! # setup_logger().ok(); // we're ok with this not succeeding.
//! trace!("Trace message");
//! debug!("Debug message");
//! info!("Info message");
//! warn!("Warning message");
//! error!("Error message");
//! # }
//! ```
//!
//! # More configuration
//!
//! Check out the [`Dispatch` documentation] and the [full example program] for more examples!
//!
//! [`fern::Dispatch::new()`]: struct.Dispatch.html#method.new
//! [`.format(|...| ...)`]: struct.Dispatch.html#method.format
//! [`chrono::Local::now()`]: https://docs.rs/chrono/0.3/chrono/offset/local/struct.Local.html#method.now
//! [`.format(`]: https://docs.rs/chrono/0.3/chrono/datetime/struct.DateTime.html#method.format
//! [`")`]: https://docs.rs/chrono/0.3/chrono/datetime/struct.DateTime.html#method.format
//! [`out.finish(format_args!(...))`]: struct.FormatCallback.html#method.finish
//! [`.level(log::LogLevelFilter::Debug)`]: struct.Dispatch.html#method.level
//! [`Dispatch::chain`]: struct.Dispatch.html#method.chain
//! [`.chain(std::io::stdout())`]: struct.Dispatch.html#method.chain
//! [`.chain(fern::log_file(...)?)`]: struct.Dispatch.html#method.chain
//! [`fern::log_file()`]: fn.log_file.html
//! [`.apply`]: struct.Dispatch.html#method.apply
//! [`format_args!()`]: https://doc.rust-lang.org/std/macro.format_args.html
//! [`println!()`]: https://doc.rust-lang.org/std/macro.println.html
//! [`std::fmt`]: https://doc.rust-lang.org/std/fmt/
//! [`chrono`]: https://github.com/chronotope/chrono
//! [time-and-date docs]: https://docs.rs/chrono/0.3.1/chrono/index.html#date-and-time
//! [the format specifier docs]: https://docs.rs/chrono/0.3.1/chrono/format/strftime/index.html#specifiers
//! [`Dispatch` documentation]: struct.Dispatch.html
//! [full example program]: https://github.com/daboross/fern/tree/master/examples/cmd-program.rs
//! [`apply`]: struct.Dispatch.html#method.apply
//! [`log`]: doc.rust-lang.org/log/
extern crate log;

use std::convert::AsRef;
use std::path::Path;
use std::fs::{File, OpenOptions};
use std::{io, fmt};

pub use builders::{Dispatch, Output};
pub use log_impl::FormatCallback;
pub use errors::InitError;

mod builders;
mod log_impl;
mod errors;

/// A type alias for a log formatter.
pub type Formatter = Fn(FormatCallback, &fmt::Arguments, &log::LogRecord) + Sync + Send + 'static;

/// A type alias for a log filter. Returning true means the record should succeed - false means it should fail.
pub type Filter = Fn(&log::LogMetadata) -> bool + Send + Sync + 'static;

/// Fern logging trait. This is necessary in order to allow for custom loggers taking in arguments that have already had
/// a custom format applied to them.
///
/// The original `log::Log` trait's `log` method only accepts messages that were created using the log macros - this
/// trait also accepts records which have had additional formatting applied to them.
pub trait FernLog: Sync + Send {
    /// Logs a log record, but with the given fmt::Arguments instead of the one contained in the LogRecord.
    ///
    /// This has access to the original record, but _should ignore_ the original `record.args()` and instead
    /// use the passed in payload.
    fn log_args(&self, payload: &fmt::Arguments, record: &log::LogRecord);
}

/// Convenience method for opening a log file with common options.
///
/// Equivalent to:
///
/// ```no_run
/// std::fs::OpenOptions::new()
///     .write(true)
///     .create(true)
///     .append(true)
///     .open("filename")
/// # ;
/// ```
///
/// See [`OpenOptions`] for more information.
///
/// [`OpenOptions`]: https://doc.rust-lang.org/std/fs/struct.OpenOptions.html
#[inline]
pub fn log_file<P: AsRef<Path>>(path: P) -> io::Result<File> {
    OpenOptions::new().write(true).create(true).append(true).open(path)
}