• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10 
11 //! A lightweight logging facade.
12 //!
13 //! The `log` crate provides a single logging API that abstracts over the
14 //! actual logging implementation. Libraries can use the logging API provided
15 //! by this crate, and the consumer of those libraries can choose the logging
16 //! implementation that is most suitable for its use case.
17 //!
18 //! If no logging implementation is selected, the facade falls back to a "noop"
19 //! implementation that ignores all log messages. The overhead in this case
20 //! is very small - just an integer load, comparison and jump.
21 //!
22 //! A log request consists of a _target_, a _level_, and a _body_. A target is a
23 //! string which defaults to the module path of the location of the log request,
24 //! though that default may be overridden. Logger implementations typically use
25 //! the target to filter requests based on some user configuration.
26 //!
27 //! # Use
28 //!
29 //! The basic use of the log crate is through the five logging macros: [`error!`],
30 //! [`warn!`], [`info!`], [`debug!`] and [`trace!`]
31 //! where `error!` represents the highest-priority log messages
32 //! and `trace!` the lowest. The log messages are filtered by configuring
33 //! the log level to exclude messages with a lower priority.
34 //! Each of these macros accept format strings similarly to [`println!`].
35 //!
36 //!
37 //! [`error!`]: ./macro.error.html
38 //! [`warn!`]: ./macro.warn.html
39 //! [`info!`]: ./macro.info.html
40 //! [`debug!`]: ./macro.debug.html
41 //! [`trace!`]: ./macro.trace.html
42 //! [`println!`]: https://doc.rust-lang.org/stable/std/macro.println.html
43 //!
44 //! ## In libraries
45 //!
46 //! Libraries should link only to the `log` crate, and use the provided
47 //! macros to log whatever information will be useful to downstream consumers.
48 //!
49 //! ### Examples
50 //!
51 //! ```edition2018
52 //! # #[derive(Debug)] pub struct Yak(String);
53 //! # impl Yak { fn shave(&mut self, _: u32) {} }
54 //! # fn find_a_razor() -> Result<u32, u32> { Ok(1) }
55 //! use log::{info, warn};
56 //!
57 //! pub fn shave_the_yak(yak: &mut Yak) {
58 //!     info!(target: "yak_events", "Commencing yak shaving for {:?}", yak);
59 //!
60 //!     loop {
61 //!         match find_a_razor() {
62 //!             Ok(razor) => {
63 //!                 info!("Razor located: {}", razor);
64 //!                 yak.shave(razor);
65 //!                 break;
66 //!             }
67 //!             Err(err) => {
68 //!                 warn!("Unable to locate a razor: {}, retrying", err);
69 //!             }
70 //!         }
71 //!     }
72 //! }
73 //! # fn main() {}
74 //! ```
75 //!
76 //! ## In executables
77 //!
78 //! Executables should choose a logging implementation and initialize it early in the
79 //! runtime of the program. Logging implementations will typically include a
80 //! function to do this. Any log messages generated before
81 //! the implementation is initialized will be ignored.
82 //!
83 //! The executable itself may use the `log` crate to log as well.
84 //!
85 //! ### Warning
86 //!
87 //! The logging system may only be initialized once.
88 //!
89 //! # Available logging implementations
90 //!
91 //! In order to produce log output executables have to use
92 //! a logger implementation compatible with the facade.
93 //! There are many available implementations to choose from,
94 //! here are some of the most popular ones:
95 //!
96 //! * Simple minimal loggers:
97 //!     * [env_logger]
98 //!     * [simple_logger]
99 //!     * [simplelog]
100 //!     * [pretty_env_logger]
101 //!     * [stderrlog]
102 //!     * [flexi_logger]
103 //! * Complex configurable frameworks:
104 //!     * [log4rs]
105 //!     * [fern]
106 //! * Adaptors for other facilities:
107 //!     * [syslog]
108 //!     * [slog-stdlog]
109 //!
110 //! # Implementing a Logger
111 //!
112 //! Loggers implement the [`Log`] trait. Here's a very basic example that simply
113 //! logs all messages at the [`Error`][level_link], [`Warn`][level_link] or
114 //! [`Info`][level_link] levels to stdout:
115 //!
116 //! ```edition2018
117 //! use log::{Record, Level, Metadata};
118 //!
119 //! struct SimpleLogger;
120 //!
121 //! impl log::Log for SimpleLogger {
122 //!     fn enabled(&self, metadata: &Metadata) -> bool {
123 //!         metadata.level() <= Level::Info
124 //!     }
125 //!
126 //!     fn log(&self, record: &Record) {
127 //!         if self.enabled(record.metadata()) {
128 //!             println!("{} - {}", record.level(), record.args());
129 //!         }
130 //!     }
131 //!
132 //!     fn flush(&self) {}
133 //! }
134 //!
135 //! # fn main() {}
136 //! ```
137 //!
138 //! Loggers are installed by calling the [`set_logger`] function. The maximum
139 //! log level also needs to be adjusted via the [`set_max_level`] function. The
140 //! logging facade uses this as an optimization to improve performance of log
141 //! messages at levels that are disabled. It's important to set it, as it
142 //! defaults to [`Off`][filter_link], so no log messages will ever be captured!
143 //! In the case of our example logger, we'll want to set the maximum log level
144 //! to [`Info`][filter_link], since we ignore any [`Debug`][level_link] or
145 //! [`Trace`][level_link] level log messages. A logging implementation should
146 //! provide a function that wraps a call to [`set_logger`] and
147 //! [`set_max_level`], handling initialization of the logger:
148 //!
149 //! ```edition2018
150 //! # use log::{Level, Metadata};
151 //! # struct SimpleLogger;
152 //! # impl log::Log for SimpleLogger {
153 //! #   fn enabled(&self, _: &Metadata) -> bool { false }
154 //! #   fn log(&self, _: &log::Record) {}
155 //! #   fn flush(&self) {}
156 //! # }
157 //! # fn main() {}
158 //! use log::{SetLoggerError, LevelFilter};
159 //!
160 //! static LOGGER: SimpleLogger = SimpleLogger;
161 //!
162 //! pub fn init() -> Result<(), SetLoggerError> {
163 //!     log::set_logger(&LOGGER)
164 //!         .map(|()| log::set_max_level(LevelFilter::Info))
165 //! }
166 //! ```
167 //!
168 //! Implementations that adjust their configurations at runtime should take care
169 //! to adjust the maximum log level as well.
170 //!
171 //! # Use with `std`
172 //!
173 //! `set_logger` requires you to provide a `&'static Log`, which can be hard to
174 //! obtain if your logger depends on some runtime configuration. The
175 //! `set_boxed_logger` function is available with the `std` Cargo feature. It is
176 //! identical to `set_logger` except that it takes a `Box<Log>` rather than a
177 //! `&'static Log`:
178 //!
179 //! ```edition2018
180 //! # use log::{Level, LevelFilter, Log, SetLoggerError, Metadata};
181 //! # struct SimpleLogger;
182 //! # impl log::Log for SimpleLogger {
183 //! #   fn enabled(&self, _: &Metadata) -> bool { false }
184 //! #   fn log(&self, _: &log::Record) {}
185 //! #   fn flush(&self) {}
186 //! # }
187 //! # fn main() {}
188 //! # #[cfg(feature = "std")]
189 //! pub fn init() -> Result<(), SetLoggerError> {
190 //!     log::set_boxed_logger(Box::new(SimpleLogger))
191 //!         .map(|()| log::set_max_level(LevelFilter::Info))
192 //! }
193 //! ```
194 //!
195 //! # Compile time filters
196 //!
197 //! Log levels can be statically disabled at compile time via Cargo features. Log invocations at
198 //! disabled levels will be skipped and will not even be present in the resulting binary.
199 //! This level is configured separately for release and debug builds. The features are:
200 //!
201 //! * `max_level_off`
202 //! * `max_level_error`
203 //! * `max_level_warn`
204 //! * `max_level_info`
205 //! * `max_level_debug`
206 //! * `max_level_trace`
207 //! * `release_max_level_off`
208 //! * `release_max_level_error`
209 //! * `release_max_level_warn`
210 //! * `release_max_level_info`
211 //! * `release_max_level_debug`
212 //! * `release_max_level_trace`
213 //!
214 //! These features control the value of the `STATIC_MAX_LEVEL` constant. The logging macros check
215 //! this value before logging a message. By default, no levels are disabled.
216 //!
217 //! Libraries should avoid using the max level features because they're global and can't be changed
218 //! once they're set.
219 //!
220 //! For example, a crate can disable trace level logs in debug builds and trace, debug, and info
221 //! level logs in release builds with the following configuration:
222 //!
223 //! ```toml
224 //! [dependencies]
225 //! log = { version = "0.4", features = ["max_level_debug", "release_max_level_warn"] }
226 //! ```
227 //! # Crate Feature Flags
228 //!
229 //! The following crate feature flags are available in addition to the filters. They are
230 //! configured in your `Cargo.toml`.
231 //!
232 //! * `std` allows use of `std` crate instead of the default `core`. Enables using `std::error` and
233 //! `set_boxed_logger` functionality.
234 //! * `serde` enables support for serialization and deserialization of `Level` and `LevelFilter`.
235 //!
236 //! ```toml
237 //! [dependencies]
238 //! log = { version = "0.4", features = ["std", "serde"] }
239 //! ```
240 //!
241 //! # Version compatibility
242 //!
243 //! The 0.3 and 0.4 versions of the `log` crate are almost entirely compatible. Log messages
244 //! made using `log` 0.3 will forward transparently to a logger implementation using `log` 0.4. Log
245 //! messages made using `log` 0.4 will forward to a logger implementation using `log` 0.3, but the
246 //! module path and file name information associated with the message will unfortunately be lost.
247 //!
248 //! [`Log`]: trait.Log.html
249 //! [level_link]: enum.Level.html
250 //! [filter_link]: enum.LevelFilter.html
251 //! [`set_logger`]: fn.set_logger.html
252 //! [`set_max_level`]: fn.set_max_level.html
253 //! [`try_set_logger_raw`]: fn.try_set_logger_raw.html
254 //! [`shutdown_logger_raw`]: fn.shutdown_logger_raw.html
255 //! [env_logger]: https://docs.rs/env_logger/*/env_logger/
256 //! [simple_logger]: https://github.com/borntyping/rust-simple_logger
257 //! [simplelog]: https://github.com/drakulix/simplelog.rs
258 //! [pretty_env_logger]: https://docs.rs/pretty_env_logger/*/pretty_env_logger/
259 //! [stderrlog]: https://docs.rs/stderrlog/*/stderrlog/
260 //! [flexi_logger]: https://docs.rs/flexi_logger/*/flexi_logger/
261 //! [syslog]: https://docs.rs/syslog/*/syslog/
262 //! [slog-stdlog]: https://docs.rs/slog-stdlog/*/slog_stdlog/
263 //! [log4rs]: https://docs.rs/log4rs/*/log4rs/
264 //! [fern]: https://docs.rs/fern/*/fern/
265 
266 #![doc(
267     html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
268     html_favicon_url = "https://www.rust-lang.org/favicon.ico",
269     html_root_url = "https://docs.rs/log/0.4.14"
270 )]
271 #![warn(missing_docs)]
272 #![deny(missing_debug_implementations)]
273 #![cfg_attr(all(not(feature = "std"), not(test)), no_std)]
274 // When compiled for the rustc compiler itself we want to make sure that this is
275 // an unstable crate
276 #![cfg_attr(rustbuild, feature(staged_api, rustc_private))]
277 #![cfg_attr(rustbuild, unstable(feature = "rustc_private", issue = "27812"))]
278 
279 #[cfg(all(not(feature = "std"), not(test)))]
280 extern crate core as std;
281 
282 #[macro_use]
283 extern crate cfg_if;
284 
285 use std::cmp;
286 #[cfg(feature = "std")]
287 use std::error;
288 use std::fmt;
289 use std::mem;
290 use std::str::FromStr;
291 
292 #[macro_use]
293 mod macros;
294 mod serde;
295 
296 #[cfg(feature = "kv_unstable")]
297 pub mod kv;
298 
299 #[cfg(has_atomics)]
300 use std::sync::atomic::{AtomicUsize, Ordering};
301 
302 #[cfg(not(has_atomics))]
303 use std::cell::Cell;
304 #[cfg(not(has_atomics))]
305 use std::sync::atomic::Ordering;
306 
307 #[cfg(not(has_atomics))]
308 struct AtomicUsize {
309     v: Cell<usize>,
310 }
311 
312 #[cfg(not(has_atomics))]
313 impl AtomicUsize {
new(v: usize) -> AtomicUsize314     const fn new(v: usize) -> AtomicUsize {
315         AtomicUsize { v: Cell::new(v) }
316     }
317 
load(&self, _order: Ordering) -> usize318     fn load(&self, _order: Ordering) -> usize {
319         self.v.get()
320     }
321 
store(&self, val: usize, _order: Ordering)322     fn store(&self, val: usize, _order: Ordering) {
323         self.v.set(val)
324     }
325 
326     #[cfg(atomic_cas)]
compare_exchange( &self, current: usize, new: usize, _success: Ordering, _failure: Ordering, ) -> Result<usize, usize>327     fn compare_exchange(
328         &self,
329         current: usize,
330         new: usize,
331         _success: Ordering,
332         _failure: Ordering,
333     ) -> Result<usize, usize> {
334         let prev = self.v.get();
335         if current == prev {
336             self.v.set(new);
337         }
338         Ok(prev)
339     }
340 }
341 
342 // Any platform without atomics is unlikely to have multiple cores, so
343 // writing via Cell will not be a race condition.
344 #[cfg(not(has_atomics))]
345 unsafe impl Sync for AtomicUsize {}
346 
347 // The LOGGER static holds a pointer to the global logger. It is protected by
348 // the STATE static which determines whether LOGGER has been initialized yet.
349 static mut LOGGER: &dyn Log = &NopLogger;
350 
351 static STATE: AtomicUsize = AtomicUsize::new(0);
352 
353 // There are three different states that we care about: the logger's
354 // uninitialized, the logger's initializing (set_logger's been called but
355 // LOGGER hasn't actually been set yet), or the logger's active.
356 const UNINITIALIZED: usize = 0;
357 const INITIALIZING: usize = 1;
358 const INITIALIZED: usize = 2;
359 
360 static MAX_LOG_LEVEL_FILTER: AtomicUsize = AtomicUsize::new(0);
361 
362 static LOG_LEVEL_NAMES: [&str; 6] = ["OFF", "ERROR", "WARN", "INFO", "DEBUG", "TRACE"];
363 
364 static SET_LOGGER_ERROR: &str = "attempted to set a logger after the logging system \
365                                  was already initialized";
366 static LEVEL_PARSE_ERROR: &str =
367     "attempted to convert a string that doesn't match an existing log level";
368 
369 /// An enum representing the available verbosity levels of the logger.
370 ///
371 /// Typical usage includes: checking if a certain `Level` is enabled with
372 /// [`log_enabled!`](macro.log_enabled.html), specifying the `Level` of
373 /// [`log!`](macro.log.html), and comparing a `Level` directly to a
374 /// [`LevelFilter`](enum.LevelFilter.html).
375 #[repr(usize)]
376 #[derive(Copy, Eq, Debug, Hash)]
377 pub enum Level {
378     /// The "error" level.
379     ///
380     /// Designates very serious errors.
381     // This way these line up with the discriminants for LevelFilter below
382     // This works because Rust treats field-less enums the same way as C does:
383     // https://doc.rust-lang.org/reference/items/enumerations.html#custom-discriminant-values-for-field-less-enumerations
384     Error = 1,
385     /// The "warn" level.
386     ///
387     /// Designates hazardous situations.
388     Warn,
389     /// The "info" level.
390     ///
391     /// Designates useful information.
392     Info,
393     /// The "debug" level.
394     ///
395     /// Designates lower priority information.
396     Debug,
397     /// The "trace" level.
398     ///
399     /// Designates very low priority, often extremely verbose, information.
400     Trace,
401 }
402 
403 impl Clone for Level {
404     #[inline]
clone(&self) -> Level405     fn clone(&self) -> Level {
406         *self
407     }
408 }
409 
410 impl PartialEq for Level {
411     #[inline]
eq(&self, other: &Level) -> bool412     fn eq(&self, other: &Level) -> bool {
413         *self as usize == *other as usize
414     }
415 }
416 
417 impl PartialEq<LevelFilter> for Level {
418     #[inline]
eq(&self, other: &LevelFilter) -> bool419     fn eq(&self, other: &LevelFilter) -> bool {
420         *self as usize == *other as usize
421     }
422 }
423 
424 impl PartialOrd for Level {
425     #[inline]
partial_cmp(&self, other: &Level) -> Option<cmp::Ordering>426     fn partial_cmp(&self, other: &Level) -> Option<cmp::Ordering> {
427         Some(self.cmp(other))
428     }
429 
430     #[inline]
lt(&self, other: &Level) -> bool431     fn lt(&self, other: &Level) -> bool {
432         (*self as usize) < *other as usize
433     }
434 
435     #[inline]
le(&self, other: &Level) -> bool436     fn le(&self, other: &Level) -> bool {
437         *self as usize <= *other as usize
438     }
439 
440     #[inline]
gt(&self, other: &Level) -> bool441     fn gt(&self, other: &Level) -> bool {
442         *self as usize > *other as usize
443     }
444 
445     #[inline]
ge(&self, other: &Level) -> bool446     fn ge(&self, other: &Level) -> bool {
447         *self as usize >= *other as usize
448     }
449 }
450 
451 impl PartialOrd<LevelFilter> for Level {
452     #[inline]
partial_cmp(&self, other: &LevelFilter) -> Option<cmp::Ordering>453     fn partial_cmp(&self, other: &LevelFilter) -> Option<cmp::Ordering> {
454         Some((*self as usize).cmp(&(*other as usize)))
455     }
456 
457     #[inline]
lt(&self, other: &LevelFilter) -> bool458     fn lt(&self, other: &LevelFilter) -> bool {
459         (*self as usize) < *other as usize
460     }
461 
462     #[inline]
le(&self, other: &LevelFilter) -> bool463     fn le(&self, other: &LevelFilter) -> bool {
464         *self as usize <= *other as usize
465     }
466 
467     #[inline]
gt(&self, other: &LevelFilter) -> bool468     fn gt(&self, other: &LevelFilter) -> bool {
469         *self as usize > *other as usize
470     }
471 
472     #[inline]
ge(&self, other: &LevelFilter) -> bool473     fn ge(&self, other: &LevelFilter) -> bool {
474         *self as usize >= *other as usize
475     }
476 }
477 
478 impl Ord for Level {
479     #[inline]
cmp(&self, other: &Level) -> cmp::Ordering480     fn cmp(&self, other: &Level) -> cmp::Ordering {
481         (*self as usize).cmp(&(*other as usize))
482     }
483 }
484 
ok_or<T, E>(t: Option<T>, e: E) -> Result<T, E>485 fn ok_or<T, E>(t: Option<T>, e: E) -> Result<T, E> {
486     match t {
487         Some(t) => Ok(t),
488         None => Err(e),
489     }
490 }
491 
492 // Reimplemented here because std::ascii is not available in libcore
eq_ignore_ascii_case(a: &str, b: &str) -> bool493 fn eq_ignore_ascii_case(a: &str, b: &str) -> bool {
494     fn to_ascii_uppercase(c: u8) -> u8 {
495         if c >= b'a' && c <= b'z' {
496             c - b'a' + b'A'
497         } else {
498             c
499         }
500     }
501 
502     if a.len() == b.len() {
503         a.bytes()
504             .zip(b.bytes())
505             .all(|(a, b)| to_ascii_uppercase(a) == to_ascii_uppercase(b))
506     } else {
507         false
508     }
509 }
510 
511 impl FromStr for Level {
512     type Err = ParseLevelError;
from_str(level: &str) -> Result<Level, Self::Err>513     fn from_str(level: &str) -> Result<Level, Self::Err> {
514         ok_or(
515             LOG_LEVEL_NAMES
516                 .iter()
517                 .position(|&name| eq_ignore_ascii_case(name, level))
518                 .into_iter()
519                 .filter(|&idx| idx != 0)
520                 .map(|idx| Level::from_usize(idx).unwrap())
521                 .next(),
522             ParseLevelError(()),
523         )
524     }
525 }
526 
527 impl fmt::Display for Level {
fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result528     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
529         fmt.pad(self.as_str())
530     }
531 }
532 
533 impl Level {
from_usize(u: usize) -> Option<Level>534     fn from_usize(u: usize) -> Option<Level> {
535         match u {
536             1 => Some(Level::Error),
537             2 => Some(Level::Warn),
538             3 => Some(Level::Info),
539             4 => Some(Level::Debug),
540             5 => Some(Level::Trace),
541             _ => None,
542         }
543     }
544 
545     /// Returns the most verbose logging level.
546     #[inline]
max() -> Level547     pub fn max() -> Level {
548         Level::Trace
549     }
550 
551     /// Converts the `Level` to the equivalent `LevelFilter`.
552     #[inline]
to_level_filter(&self) -> LevelFilter553     pub fn to_level_filter(&self) -> LevelFilter {
554         LevelFilter::from_usize(*self as usize).unwrap()
555     }
556 
557     /// Returns the string representation of the `Level`.
558     ///
559     /// This returns the same string as the `fmt::Display` implementation.
as_str(&self) -> &'static str560     pub fn as_str(&self) -> &'static str {
561         LOG_LEVEL_NAMES[*self as usize]
562     }
563 }
564 
565 /// An enum representing the available verbosity level filters of the logger.
566 ///
567 /// A `LevelFilter` may be compared directly to a [`Level`]. Use this type
568 /// to get and set the maximum log level with [`max_level()`] and [`set_max_level`].
569 ///
570 /// [`Level`]: enum.Level.html
571 /// [`max_level()`]: fn.max_level.html
572 /// [`set_max_level`]: fn.set_max_level.html
573 #[repr(usize)]
574 #[derive(Copy, Eq, Debug, Hash)]
575 pub enum LevelFilter {
576     /// A level lower than all log levels.
577     Off,
578     /// Corresponds to the `Error` log level.
579     Error,
580     /// Corresponds to the `Warn` log level.
581     Warn,
582     /// Corresponds to the `Info` log level.
583     Info,
584     /// Corresponds to the `Debug` log level.
585     Debug,
586     /// Corresponds to the `Trace` log level.
587     Trace,
588 }
589 
590 // Deriving generates terrible impls of these traits
591 
592 impl Clone for LevelFilter {
593     #[inline]
clone(&self) -> LevelFilter594     fn clone(&self) -> LevelFilter {
595         *self
596     }
597 }
598 
599 impl PartialEq for LevelFilter {
600     #[inline]
eq(&self, other: &LevelFilter) -> bool601     fn eq(&self, other: &LevelFilter) -> bool {
602         *self as usize == *other as usize
603     }
604 }
605 
606 impl PartialEq<Level> for LevelFilter {
607     #[inline]
eq(&self, other: &Level) -> bool608     fn eq(&self, other: &Level) -> bool {
609         other.eq(self)
610     }
611 }
612 
613 impl PartialOrd for LevelFilter {
614     #[inline]
partial_cmp(&self, other: &LevelFilter) -> Option<cmp::Ordering>615     fn partial_cmp(&self, other: &LevelFilter) -> Option<cmp::Ordering> {
616         Some(self.cmp(other))
617     }
618 
619     #[inline]
lt(&self, other: &LevelFilter) -> bool620     fn lt(&self, other: &LevelFilter) -> bool {
621         (*self as usize) < *other as usize
622     }
623 
624     #[inline]
le(&self, other: &LevelFilter) -> bool625     fn le(&self, other: &LevelFilter) -> bool {
626         *self as usize <= *other as usize
627     }
628 
629     #[inline]
gt(&self, other: &LevelFilter) -> bool630     fn gt(&self, other: &LevelFilter) -> bool {
631         *self as usize > *other as usize
632     }
633 
634     #[inline]
ge(&self, other: &LevelFilter) -> bool635     fn ge(&self, other: &LevelFilter) -> bool {
636         *self as usize >= *other as usize
637     }
638 }
639 
640 impl PartialOrd<Level> for LevelFilter {
641     #[inline]
partial_cmp(&self, other: &Level) -> Option<cmp::Ordering>642     fn partial_cmp(&self, other: &Level) -> Option<cmp::Ordering> {
643         Some((*self as usize).cmp(&(*other as usize)))
644     }
645 
646     #[inline]
lt(&self, other: &Level) -> bool647     fn lt(&self, other: &Level) -> bool {
648         (*self as usize) < *other as usize
649     }
650 
651     #[inline]
le(&self, other: &Level) -> bool652     fn le(&self, other: &Level) -> bool {
653         *self as usize <= *other as usize
654     }
655 
656     #[inline]
gt(&self, other: &Level) -> bool657     fn gt(&self, other: &Level) -> bool {
658         *self as usize > *other as usize
659     }
660 
661     #[inline]
ge(&self, other: &Level) -> bool662     fn ge(&self, other: &Level) -> bool {
663         *self as usize >= *other as usize
664     }
665 }
666 
667 impl Ord for LevelFilter {
668     #[inline]
cmp(&self, other: &LevelFilter) -> cmp::Ordering669     fn cmp(&self, other: &LevelFilter) -> cmp::Ordering {
670         (*self as usize).cmp(&(*other as usize))
671     }
672 }
673 
674 impl FromStr for LevelFilter {
675     type Err = ParseLevelError;
from_str(level: &str) -> Result<LevelFilter, Self::Err>676     fn from_str(level: &str) -> Result<LevelFilter, Self::Err> {
677         ok_or(
678             LOG_LEVEL_NAMES
679                 .iter()
680                 .position(|&name| eq_ignore_ascii_case(name, level))
681                 .map(|p| LevelFilter::from_usize(p).unwrap()),
682             ParseLevelError(()),
683         )
684     }
685 }
686 
687 impl fmt::Display for LevelFilter {
fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result688     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
689         fmt.pad(self.as_str())
690     }
691 }
692 
693 impl LevelFilter {
from_usize(u: usize) -> Option<LevelFilter>694     fn from_usize(u: usize) -> Option<LevelFilter> {
695         match u {
696             0 => Some(LevelFilter::Off),
697             1 => Some(LevelFilter::Error),
698             2 => Some(LevelFilter::Warn),
699             3 => Some(LevelFilter::Info),
700             4 => Some(LevelFilter::Debug),
701             5 => Some(LevelFilter::Trace),
702             _ => None,
703         }
704     }
705     /// Returns the most verbose logging level filter.
706     #[inline]
max() -> LevelFilter707     pub fn max() -> LevelFilter {
708         LevelFilter::Trace
709     }
710 
711     /// Converts `self` to the equivalent `Level`.
712     ///
713     /// Returns `None` if `self` is `LevelFilter::Off`.
714     #[inline]
to_level(&self) -> Option<Level>715     pub fn to_level(&self) -> Option<Level> {
716         Level::from_usize(*self as usize)
717     }
718 
719     /// Returns the string representation of the `LevelFilter`.
720     ///
721     /// This returns the same string as the `fmt::Display` implementation.
as_str(&self) -> &'static str722     pub fn as_str(&self) -> &'static str {
723         LOG_LEVEL_NAMES[*self as usize]
724     }
725 }
726 
727 #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
728 enum MaybeStaticStr<'a> {
729     Static(&'static str),
730     Borrowed(&'a str),
731 }
732 
733 impl<'a> MaybeStaticStr<'a> {
734     #[inline]
get(&self) -> &'a str735     fn get(&self) -> &'a str {
736         match *self {
737             MaybeStaticStr::Static(s) => s,
738             MaybeStaticStr::Borrowed(s) => s,
739         }
740     }
741 }
742 
743 /// The "payload" of a log message.
744 ///
745 /// # Use
746 ///
747 /// `Record` structures are passed as parameters to the [`log`][method.log]
748 /// method of the [`Log`] trait. Logger implementors manipulate these
749 /// structures in order to display log messages. `Record`s are automatically
750 /// created by the [`log!`] macro and so are not seen by log users.
751 ///
752 /// Note that the [`level()`] and [`target()`] accessors are equivalent to
753 /// `self.metadata().level()` and `self.metadata().target()` respectively.
754 /// These methods are provided as a convenience for users of this structure.
755 ///
756 /// # Example
757 ///
758 /// The following example shows a simple logger that displays the level,
759 /// module path, and message of any `Record` that is passed to it.
760 ///
761 /// ```edition2018
762 /// struct SimpleLogger;
763 ///
764 /// impl log::Log for SimpleLogger {
765 ///    fn enabled(&self, metadata: &log::Metadata) -> bool {
766 ///        true
767 ///    }
768 ///
769 ///    fn log(&self, record: &log::Record) {
770 ///        if !self.enabled(record.metadata()) {
771 ///            return;
772 ///        }
773 ///
774 ///        println!("{}:{} -- {}",
775 ///                 record.level(),
776 ///                 record.target(),
777 ///                 record.args());
778 ///    }
779 ///    fn flush(&self) {}
780 /// }
781 /// ```
782 ///
783 /// [method.log]: trait.Log.html#tymethod.log
784 /// [`Log`]: trait.Log.html
785 /// [`log!`]: macro.log.html
786 /// [`level()`]: struct.Record.html#method.level
787 /// [`target()`]: struct.Record.html#method.target
788 #[derive(Clone, Debug)]
789 pub struct Record<'a> {
790     metadata: Metadata<'a>,
791     args: fmt::Arguments<'a>,
792     module_path: Option<MaybeStaticStr<'a>>,
793     file: Option<MaybeStaticStr<'a>>,
794     line: Option<u32>,
795     #[cfg(feature = "kv_unstable")]
796     key_values: KeyValues<'a>,
797 }
798 
799 // This wrapper type is only needed so we can
800 // `#[derive(Debug)]` on `Record`. It also
801 // provides a useful `Debug` implementation for
802 // the underlying `Source`.
803 #[cfg(feature = "kv_unstable")]
804 #[derive(Clone)]
805 struct KeyValues<'a>(&'a dyn kv::Source);
806 
807 #[cfg(feature = "kv_unstable")]
808 impl<'a> fmt::Debug for KeyValues<'a> {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result809     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
810         let mut visitor = f.debug_map();
811         self.0.visit(&mut visitor).map_err(|_| fmt::Error)?;
812         visitor.finish()
813     }
814 }
815 
816 impl<'a> Record<'a> {
817     /// Returns a new builder.
818     #[inline]
builder() -> RecordBuilder<'a>819     pub fn builder() -> RecordBuilder<'a> {
820         RecordBuilder::new()
821     }
822 
823     /// The message body.
824     #[inline]
args(&self) -> &fmt::Arguments<'a>825     pub fn args(&self) -> &fmt::Arguments<'a> {
826         &self.args
827     }
828 
829     /// Metadata about the log directive.
830     #[inline]
metadata(&self) -> &Metadata<'a>831     pub fn metadata(&self) -> &Metadata<'a> {
832         &self.metadata
833     }
834 
835     /// The verbosity level of the message.
836     #[inline]
level(&self) -> Level837     pub fn level(&self) -> Level {
838         self.metadata.level()
839     }
840 
841     /// The name of the target of the directive.
842     #[inline]
target(&self) -> &'a str843     pub fn target(&self) -> &'a str {
844         self.metadata.target()
845     }
846 
847     /// The module path of the message.
848     #[inline]
module_path(&self) -> Option<&'a str>849     pub fn module_path(&self) -> Option<&'a str> {
850         self.module_path.map(|s| s.get())
851     }
852 
853     /// The module path of the message, if it is a `'static` string.
854     #[inline]
module_path_static(&self) -> Option<&'static str>855     pub fn module_path_static(&self) -> Option<&'static str> {
856         match self.module_path {
857             Some(MaybeStaticStr::Static(s)) => Some(s),
858             _ => None,
859         }
860     }
861 
862     /// The source file containing the message.
863     #[inline]
file(&self) -> Option<&'a str>864     pub fn file(&self) -> Option<&'a str> {
865         self.file.map(|s| s.get())
866     }
867 
868     /// The module path of the message, if it is a `'static` string.
869     #[inline]
file_static(&self) -> Option<&'static str>870     pub fn file_static(&self) -> Option<&'static str> {
871         match self.file {
872             Some(MaybeStaticStr::Static(s)) => Some(s),
873             _ => None,
874         }
875     }
876 
877     /// The line containing the message.
878     #[inline]
line(&self) -> Option<u32>879     pub fn line(&self) -> Option<u32> {
880         self.line
881     }
882 
883     /// The structued key-value pairs associated with the message.
884     #[cfg(feature = "kv_unstable")]
885     #[inline]
key_values(&self) -> &dyn kv::Source886     pub fn key_values(&self) -> &dyn kv::Source {
887         self.key_values.0
888     }
889 
890     /// Create a new [`RecordBuilder`](struct.RecordBuilder.html) based on this record.
891     #[cfg(feature = "kv_unstable")]
892     #[inline]
to_builder(&self) -> RecordBuilder893     pub fn to_builder(&self) -> RecordBuilder {
894         RecordBuilder {
895             record: Record {
896                 metadata: Metadata {
897                     level: self.metadata.level,
898                     target: self.metadata.target,
899                 },
900                 args: self.args,
901                 module_path: self.module_path,
902                 file: self.file,
903                 line: self.line,
904                 key_values: self.key_values.clone(),
905             },
906         }
907     }
908 }
909 
910 /// Builder for [`Record`](struct.Record.html).
911 ///
912 /// Typically should only be used by log library creators or for testing and "shim loggers".
913 /// The `RecordBuilder` can set the different parameters of `Record` object, and returns
914 /// the created object when `build` is called.
915 ///
916 /// # Examples
917 ///
918 ///
919 /// ```edition2018
920 /// use log::{Level, Record};
921 ///
922 /// let record = Record::builder()
923 ///                 .args(format_args!("Error!"))
924 ///                 .level(Level::Error)
925 ///                 .target("myApp")
926 ///                 .file(Some("server.rs"))
927 ///                 .line(Some(144))
928 ///                 .module_path(Some("server"))
929 ///                 .build();
930 /// ```
931 ///
932 /// Alternatively, use [`MetadataBuilder`](struct.MetadataBuilder.html):
933 ///
934 /// ```edition2018
935 /// use log::{Record, Level, MetadataBuilder};
936 ///
937 /// let error_metadata = MetadataBuilder::new()
938 ///                         .target("myApp")
939 ///                         .level(Level::Error)
940 ///                         .build();
941 ///
942 /// let record = Record::builder()
943 ///                 .metadata(error_metadata)
944 ///                 .args(format_args!("Error!"))
945 ///                 .line(Some(433))
946 ///                 .file(Some("app.rs"))
947 ///                 .module_path(Some("server"))
948 ///                 .build();
949 /// ```
950 #[derive(Debug)]
951 pub struct RecordBuilder<'a> {
952     record: Record<'a>,
953 }
954 
955 impl<'a> RecordBuilder<'a> {
956     /// Construct new `RecordBuilder`.
957     ///
958     /// The default options are:
959     ///
960     /// - `args`: [`format_args!("")`]
961     /// - `metadata`: [`Metadata::builder().build()`]
962     /// - `module_path`: `None`
963     /// - `file`: `None`
964     /// - `line`: `None`
965     ///
966     /// [`format_args!("")`]: https://doc.rust-lang.org/std/macro.format_args.html
967     /// [`Metadata::builder().build()`]: struct.MetadataBuilder.html#method.build
968     #[inline]
new() -> RecordBuilder<'a>969     pub fn new() -> RecordBuilder<'a> {
970         RecordBuilder {
971             record: Record {
972                 args: format_args!(""),
973                 metadata: Metadata::builder().build(),
974                 module_path: None,
975                 file: None,
976                 line: None,
977                 #[cfg(feature = "kv_unstable")]
978                 key_values: KeyValues(&Option::None::<(kv::Key, kv::Value)>),
979             },
980         }
981     }
982 
983     /// Set [`args`](struct.Record.html#method.args).
984     #[inline]
args(&mut self, args: fmt::Arguments<'a>) -> &mut RecordBuilder<'a>985     pub fn args(&mut self, args: fmt::Arguments<'a>) -> &mut RecordBuilder<'a> {
986         self.record.args = args;
987         self
988     }
989 
990     /// Set [`metadata`](struct.Record.html#method.metadata). Construct a `Metadata` object with [`MetadataBuilder`](struct.MetadataBuilder.html).
991     #[inline]
metadata(&mut self, metadata: Metadata<'a>) -> &mut RecordBuilder<'a>992     pub fn metadata(&mut self, metadata: Metadata<'a>) -> &mut RecordBuilder<'a> {
993         self.record.metadata = metadata;
994         self
995     }
996 
997     /// Set [`Metadata::level`](struct.Metadata.html#method.level).
998     #[inline]
level(&mut self, level: Level) -> &mut RecordBuilder<'a>999     pub fn level(&mut self, level: Level) -> &mut RecordBuilder<'a> {
1000         self.record.metadata.level = level;
1001         self
1002     }
1003 
1004     /// Set [`Metadata::target`](struct.Metadata.html#method.target)
1005     #[inline]
target(&mut self, target: &'a str) -> &mut RecordBuilder<'a>1006     pub fn target(&mut self, target: &'a str) -> &mut RecordBuilder<'a> {
1007         self.record.metadata.target = target;
1008         self
1009     }
1010 
1011     /// Set [`module_path`](struct.Record.html#method.module_path)
1012     #[inline]
module_path(&mut self, path: Option<&'a str>) -> &mut RecordBuilder<'a>1013     pub fn module_path(&mut self, path: Option<&'a str>) -> &mut RecordBuilder<'a> {
1014         self.record.module_path = path.map(MaybeStaticStr::Borrowed);
1015         self
1016     }
1017 
1018     /// Set [`module_path`](struct.Record.html#method.module_path) to a `'static` string
1019     #[inline]
module_path_static(&mut self, path: Option<&'static str>) -> &mut RecordBuilder<'a>1020     pub fn module_path_static(&mut self, path: Option<&'static str>) -> &mut RecordBuilder<'a> {
1021         self.record.module_path = path.map(MaybeStaticStr::Static);
1022         self
1023     }
1024 
1025     /// Set [`file`](struct.Record.html#method.file)
1026     #[inline]
file(&mut self, file: Option<&'a str>) -> &mut RecordBuilder<'a>1027     pub fn file(&mut self, file: Option<&'a str>) -> &mut RecordBuilder<'a> {
1028         self.record.file = file.map(MaybeStaticStr::Borrowed);
1029         self
1030     }
1031 
1032     /// Set [`file`](struct.Record.html#method.file) to a `'static` string.
1033     #[inline]
file_static(&mut self, file: Option<&'static str>) -> &mut RecordBuilder<'a>1034     pub fn file_static(&mut self, file: Option<&'static str>) -> &mut RecordBuilder<'a> {
1035         self.record.file = file.map(MaybeStaticStr::Static);
1036         self
1037     }
1038 
1039     /// Set [`line`](struct.Record.html#method.line)
1040     #[inline]
line(&mut self, line: Option<u32>) -> &mut RecordBuilder<'a>1041     pub fn line(&mut self, line: Option<u32>) -> &mut RecordBuilder<'a> {
1042         self.record.line = line;
1043         self
1044     }
1045 
1046     /// Set [`key_values`](struct.Record.html#method.key_values)
1047     #[cfg(feature = "kv_unstable")]
1048     #[inline]
key_values(&mut self, kvs: &'a dyn kv::Source) -> &mut RecordBuilder<'a>1049     pub fn key_values(&mut self, kvs: &'a dyn kv::Source) -> &mut RecordBuilder<'a> {
1050         self.record.key_values = KeyValues(kvs);
1051         self
1052     }
1053 
1054     /// Invoke the builder and return a `Record`
1055     #[inline]
build(&self) -> Record<'a>1056     pub fn build(&self) -> Record<'a> {
1057         self.record.clone()
1058     }
1059 }
1060 
1061 /// Metadata about a log message.
1062 ///
1063 /// # Use
1064 ///
1065 /// `Metadata` structs are created when users of the library use
1066 /// logging macros.
1067 ///
1068 /// They are consumed by implementations of the `Log` trait in the
1069 /// `enabled` method.
1070 ///
1071 /// `Record`s use `Metadata` to determine the log message's severity
1072 /// and target.
1073 ///
1074 /// Users should use the `log_enabled!` macro in their code to avoid
1075 /// constructing expensive log messages.
1076 ///
1077 /// # Examples
1078 ///
1079 /// ```edition2018
1080 /// use log::{Record, Level, Metadata};
1081 ///
1082 /// struct MyLogger;
1083 ///
1084 /// impl log::Log for MyLogger {
1085 ///     fn enabled(&self, metadata: &Metadata) -> bool {
1086 ///         metadata.level() <= Level::Info
1087 ///     }
1088 ///
1089 ///     fn log(&self, record: &Record) {
1090 ///         if self.enabled(record.metadata()) {
1091 ///             println!("{} - {}", record.level(), record.args());
1092 ///         }
1093 ///     }
1094 ///     fn flush(&self) {}
1095 /// }
1096 ///
1097 /// # fn main(){}
1098 /// ```
1099 #[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
1100 pub struct Metadata<'a> {
1101     level: Level,
1102     target: &'a str,
1103 }
1104 
1105 impl<'a> Metadata<'a> {
1106     /// Returns a new builder.
1107     #[inline]
builder() -> MetadataBuilder<'a>1108     pub fn builder() -> MetadataBuilder<'a> {
1109         MetadataBuilder::new()
1110     }
1111 
1112     /// The verbosity level of the message.
1113     #[inline]
level(&self) -> Level1114     pub fn level(&self) -> Level {
1115         self.level
1116     }
1117 
1118     /// The name of the target of the directive.
1119     #[inline]
target(&self) -> &'a str1120     pub fn target(&self) -> &'a str {
1121         self.target
1122     }
1123 }
1124 
1125 /// Builder for [`Metadata`](struct.Metadata.html).
1126 ///
1127 /// Typically should only be used by log library creators or for testing and "shim loggers".
1128 /// The `MetadataBuilder` can set the different parameters of a `Metadata` object, and returns
1129 /// the created object when `build` is called.
1130 ///
1131 /// # Example
1132 ///
1133 /// ```edition2018
1134 /// let target = "myApp";
1135 /// use log::{Level, MetadataBuilder};
1136 /// let metadata = MetadataBuilder::new()
1137 ///                     .level(Level::Debug)
1138 ///                     .target(target)
1139 ///                     .build();
1140 /// ```
1141 #[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
1142 pub struct MetadataBuilder<'a> {
1143     metadata: Metadata<'a>,
1144 }
1145 
1146 impl<'a> MetadataBuilder<'a> {
1147     /// Construct a new `MetadataBuilder`.
1148     ///
1149     /// The default options are:
1150     ///
1151     /// - `level`: `Level::Info`
1152     /// - `target`: `""`
1153     #[inline]
new() -> MetadataBuilder<'a>1154     pub fn new() -> MetadataBuilder<'a> {
1155         MetadataBuilder {
1156             metadata: Metadata {
1157                 level: Level::Info,
1158                 target: "",
1159             },
1160         }
1161     }
1162 
1163     /// Setter for [`level`](struct.Metadata.html#method.level).
1164     #[inline]
level(&mut self, arg: Level) -> &mut MetadataBuilder<'a>1165     pub fn level(&mut self, arg: Level) -> &mut MetadataBuilder<'a> {
1166         self.metadata.level = arg;
1167         self
1168     }
1169 
1170     /// Setter for [`target`](struct.Metadata.html#method.target).
1171     #[inline]
target(&mut self, target: &'a str) -> &mut MetadataBuilder<'a>1172     pub fn target(&mut self, target: &'a str) -> &mut MetadataBuilder<'a> {
1173         self.metadata.target = target;
1174         self
1175     }
1176 
1177     /// Returns a `Metadata` object.
1178     #[inline]
build(&self) -> Metadata<'a>1179     pub fn build(&self) -> Metadata<'a> {
1180         self.metadata.clone()
1181     }
1182 }
1183 
1184 /// A trait encapsulating the operations required of a logger.
1185 pub trait Log: Sync + Send {
1186     /// Determines if a log message with the specified metadata would be
1187     /// logged.
1188     ///
1189     /// This is used by the `log_enabled!` macro to allow callers to avoid
1190     /// expensive computation of log message arguments if the message would be
1191     /// discarded anyway.
enabled(&self, metadata: &Metadata) -> bool1192     fn enabled(&self, metadata: &Metadata) -> bool;
1193 
1194     /// Logs the `Record`.
1195     ///
1196     /// Note that `enabled` is *not* necessarily called before this method.
1197     /// Implementations of `log` should perform all necessary filtering
1198     /// internally.
log(&self, record: &Record)1199     fn log(&self, record: &Record);
1200 
1201     /// Flushes any buffered records.
flush(&self)1202     fn flush(&self);
1203 }
1204 
1205 // Just used as a dummy initial value for LOGGER
1206 struct NopLogger;
1207 
1208 impl Log for NopLogger {
enabled(&self, _: &Metadata) -> bool1209     fn enabled(&self, _: &Metadata) -> bool {
1210         false
1211     }
1212 
log(&self, _: &Record)1213     fn log(&self, _: &Record) {}
flush(&self)1214     fn flush(&self) {}
1215 }
1216 
1217 #[cfg(feature = "std")]
1218 impl<T> Log for std::boxed::Box<T>
1219 where
1220     T: ?Sized + Log,
1221 {
enabled(&self, metadata: &Metadata) -> bool1222     fn enabled(&self, metadata: &Metadata) -> bool {
1223         self.as_ref().enabled(metadata)
1224     }
1225 
log(&self, record: &Record)1226     fn log(&self, record: &Record) {
1227         self.as_ref().log(record)
1228     }
flush(&self)1229     fn flush(&self) {
1230         self.as_ref().flush()
1231     }
1232 }
1233 
1234 /// Sets the global maximum log level.
1235 ///
1236 /// Generally, this should only be called by the active logging implementation.
1237 #[inline]
set_max_level(level: LevelFilter)1238 pub fn set_max_level(level: LevelFilter) {
1239     MAX_LOG_LEVEL_FILTER.store(level as usize, Ordering::SeqCst)
1240 }
1241 
1242 /// Returns the current maximum log level.
1243 ///
1244 /// The [`log!`], [`error!`], [`warn!`], [`info!`], [`debug!`], and [`trace!`] macros check
1245 /// this value and discard any message logged at a higher level. The maximum
1246 /// log level is set by the [`set_max_level`] function.
1247 ///
1248 /// [`log!`]: macro.log.html
1249 /// [`error!`]: macro.error.html
1250 /// [`warn!`]: macro.warn.html
1251 /// [`info!`]: macro.info.html
1252 /// [`debug!`]: macro.debug.html
1253 /// [`trace!`]: macro.trace.html
1254 /// [`set_max_level`]: fn.set_max_level.html
1255 #[inline(always)]
max_level() -> LevelFilter1256 pub fn max_level() -> LevelFilter {
1257     // Since `LevelFilter` is `repr(usize)`,
1258     // this transmute is sound if and only if `MAX_LOG_LEVEL_FILTER`
1259     // is set to a usize that is a valid discriminant for `LevelFilter`.
1260     // Since `MAX_LOG_LEVEL_FILTER` is private, the only time it's set
1261     // is by `set_max_level` above, i.e. by casting a `LevelFilter` to `usize`.
1262     // So any usize stored in `MAX_LOG_LEVEL_FILTER` is a valid discriminant.
1263     unsafe { mem::transmute(MAX_LOG_LEVEL_FILTER.load(Ordering::Relaxed)) }
1264 }
1265 
1266 /// Sets the global logger to a `Box<Log>`.
1267 ///
1268 /// This is a simple convenience wrapper over `set_logger`, which takes a
1269 /// `Box<Log>` rather than a `&'static Log`. See the documentation for
1270 /// [`set_logger`] for more details.
1271 ///
1272 /// Requires the `std` feature.
1273 ///
1274 /// # Errors
1275 ///
1276 /// An error is returned if a logger has already been set.
1277 ///
1278 /// [`set_logger`]: fn.set_logger.html
1279 #[cfg(all(feature = "std", atomic_cas))]
set_boxed_logger(logger: Box<dyn Log>) -> Result<(), SetLoggerError>1280 pub fn set_boxed_logger(logger: Box<dyn Log>) -> Result<(), SetLoggerError> {
1281     set_logger_inner(|| Box::leak(logger))
1282 }
1283 
1284 /// Sets the global logger to a `&'static Log`.
1285 ///
1286 /// This function may only be called once in the lifetime of a program. Any log
1287 /// events that occur before the call to `set_logger` completes will be ignored.
1288 ///
1289 /// This function does not typically need to be called manually. Logger
1290 /// implementations should provide an initialization method that installs the
1291 /// logger internally.
1292 ///
1293 /// # Availability
1294 ///
1295 /// This method is available even when the `std` feature is disabled. However,
1296 /// it is currently unavailable on `thumbv6` targets, which lack support for
1297 /// some atomic operations which are used by this function. Even on those
1298 /// targets, [`set_logger_racy`] will be available.
1299 ///
1300 /// # Errors
1301 ///
1302 /// An error is returned if a logger has already been set.
1303 ///
1304 /// # Examples
1305 ///
1306 /// ```edition2018
1307 /// use log::{error, info, warn, Record, Level, Metadata, LevelFilter};
1308 ///
1309 /// static MY_LOGGER: MyLogger = MyLogger;
1310 ///
1311 /// struct MyLogger;
1312 ///
1313 /// impl log::Log for MyLogger {
1314 ///     fn enabled(&self, metadata: &Metadata) -> bool {
1315 ///         metadata.level() <= Level::Info
1316 ///     }
1317 ///
1318 ///     fn log(&self, record: &Record) {
1319 ///         if self.enabled(record.metadata()) {
1320 ///             println!("{} - {}", record.level(), record.args());
1321 ///         }
1322 ///     }
1323 ///     fn flush(&self) {}
1324 /// }
1325 ///
1326 /// # fn main(){
1327 /// log::set_logger(&MY_LOGGER).unwrap();
1328 /// log::set_max_level(LevelFilter::Info);
1329 ///
1330 /// info!("hello log");
1331 /// warn!("warning");
1332 /// error!("oops");
1333 /// # }
1334 /// ```
1335 ///
1336 /// [`set_logger_racy`]: fn.set_logger_racy.html
1337 #[cfg(atomic_cas)]
set_logger(logger: &'static dyn Log) -> Result<(), SetLoggerError>1338 pub fn set_logger(logger: &'static dyn Log) -> Result<(), SetLoggerError> {
1339     set_logger_inner(|| logger)
1340 }
1341 
1342 #[cfg(atomic_cas)]
set_logger_inner<F>(make_logger: F) -> Result<(), SetLoggerError> where F: FnOnce() -> &'static dyn Log,1343 fn set_logger_inner<F>(make_logger: F) -> Result<(), SetLoggerError>
1344 where
1345     F: FnOnce() -> &'static dyn Log,
1346 {
1347     let old_state = match STATE.compare_exchange(
1348         UNINITIALIZED,
1349         INITIALIZING,
1350         Ordering::SeqCst,
1351         Ordering::SeqCst,
1352     ) {
1353         Ok(s) | Err(s) => s,
1354     };
1355     match old_state {
1356         UNINITIALIZED => {
1357             unsafe {
1358                 LOGGER = make_logger();
1359             }
1360             STATE.store(INITIALIZED, Ordering::SeqCst);
1361             Ok(())
1362         }
1363         INITIALIZING => {
1364             while STATE.load(Ordering::SeqCst) == INITIALIZING {
1365                 std::sync::atomic::spin_loop_hint();
1366             }
1367             Err(SetLoggerError(()))
1368         }
1369         _ => Err(SetLoggerError(())),
1370     }
1371 }
1372 
1373 /// A thread-unsafe version of [`set_logger`].
1374 ///
1375 /// This function is available on all platforms, even those that do not have
1376 /// support for atomics that is needed by [`set_logger`].
1377 ///
1378 /// In almost all cases, [`set_logger`] should be preferred.
1379 ///
1380 /// # Safety
1381 ///
1382 /// This function is only safe to call when no other logger initialization
1383 /// function is called while this function still executes.
1384 ///
1385 /// This can be upheld by (for example) making sure that **there are no other
1386 /// threads**, and (on embedded) that **interrupts are disabled**.
1387 ///
1388 /// It is safe to use other logging functions while this function runs
1389 /// (including all logging macros).
1390 ///
1391 /// [`set_logger`]: fn.set_logger.html
set_logger_racy(logger: &'static dyn Log) -> Result<(), SetLoggerError>1392 pub unsafe fn set_logger_racy(logger: &'static dyn Log) -> Result<(), SetLoggerError> {
1393     match STATE.load(Ordering::SeqCst) {
1394         UNINITIALIZED => {
1395             LOGGER = logger;
1396             STATE.store(INITIALIZED, Ordering::SeqCst);
1397             Ok(())
1398         }
1399         INITIALIZING => {
1400             // This is just plain UB, since we were racing another initialization function
1401             unreachable!("set_logger_racy must not be used with other initialization functions")
1402         }
1403         _ => Err(SetLoggerError(())),
1404     }
1405 }
1406 
1407 /// The type returned by [`set_logger`] if [`set_logger`] has already been called.
1408 ///
1409 /// [`set_logger`]: fn.set_logger.html
1410 #[allow(missing_copy_implementations)]
1411 #[derive(Debug)]
1412 pub struct SetLoggerError(());
1413 
1414 impl fmt::Display for SetLoggerError {
fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result1415     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1416         fmt.write_str(SET_LOGGER_ERROR)
1417     }
1418 }
1419 
1420 // The Error trait is not available in libcore
1421 #[cfg(feature = "std")]
1422 impl error::Error for SetLoggerError {}
1423 
1424 /// The type returned by [`from_str`] when the string doesn't match any of the log levels.
1425 ///
1426 /// [`from_str`]: https://doc.rust-lang.org/std/str/trait.FromStr.html#tymethod.from_str
1427 #[allow(missing_copy_implementations)]
1428 #[derive(Debug, PartialEq)]
1429 pub struct ParseLevelError(());
1430 
1431 impl fmt::Display for ParseLevelError {
fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result1432     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1433         fmt.write_str(LEVEL_PARSE_ERROR)
1434     }
1435 }
1436 
1437 // The Error trait is not available in libcore
1438 #[cfg(feature = "std")]
1439 impl error::Error for ParseLevelError {}
1440 
1441 /// Returns a reference to the logger.
1442 ///
1443 /// If a logger has not been set, a no-op implementation is returned.
logger() -> &'static dyn Log1444 pub fn logger() -> &'static dyn Log {
1445     if STATE.load(Ordering::SeqCst) != INITIALIZED {
1446         static NOP: NopLogger = NopLogger;
1447         &NOP
1448     } else {
1449         unsafe { LOGGER }
1450     }
1451 }
1452 
1453 // WARNING: this is not part of the crate's public API and is subject to change at any time
1454 #[doc(hidden)]
__private_api_log( args: fmt::Arguments, level: Level, &(target, module_path, file, line): &(&str, &'static str, &'static str, u32), )1455 pub fn __private_api_log(
1456     args: fmt::Arguments,
1457     level: Level,
1458     &(target, module_path, file, line): &(&str, &'static str, &'static str, u32),
1459 ) {
1460     logger().log(
1461         &Record::builder()
1462             .args(args)
1463             .level(level)
1464             .target(target)
1465             .module_path_static(Some(module_path))
1466             .file_static(Some(file))
1467             .line(Some(line))
1468             .build(),
1469     );
1470 }
1471 
1472 // WARNING: this is not part of the crate's public API and is subject to change at any time
1473 #[doc(hidden)]
__private_api_enabled(level: Level, target: &str) -> bool1474 pub fn __private_api_enabled(level: Level, target: &str) -> bool {
1475     logger().enabled(&Metadata::builder().level(level).target(target).build())
1476 }
1477 
1478 /// The statically resolved maximum log level.
1479 ///
1480 /// See the crate level documentation for information on how to configure this.
1481 ///
1482 /// This value is checked by the log macros, but not by the `Log`ger returned by
1483 /// the [`logger`] function. Code that manually calls functions on that value
1484 /// should compare the level against this value.
1485 ///
1486 /// [`logger`]: fn.logger.html
1487 pub const STATIC_MAX_LEVEL: LevelFilter = MAX_LEVEL_INNER;
1488 
1489 cfg_if! {
1490     if #[cfg(all(not(debug_assertions), feature = "release_max_level_off"))] {
1491         const MAX_LEVEL_INNER: LevelFilter = LevelFilter::Off;
1492     } else if #[cfg(all(not(debug_assertions), feature = "release_max_level_error"))] {
1493         const MAX_LEVEL_INNER: LevelFilter = LevelFilter::Error;
1494     } else if #[cfg(all(not(debug_assertions), feature = "release_max_level_warn"))] {
1495         const MAX_LEVEL_INNER: LevelFilter = LevelFilter::Warn;
1496     } else if #[cfg(all(not(debug_assertions), feature = "release_max_level_info"))] {
1497         const MAX_LEVEL_INNER: LevelFilter = LevelFilter::Info;
1498     } else if #[cfg(all(not(debug_assertions), feature = "release_max_level_debug"))] {
1499         const MAX_LEVEL_INNER: LevelFilter = LevelFilter::Debug;
1500     } else if #[cfg(all(not(debug_assertions), feature = "release_max_level_trace"))] {
1501         const MAX_LEVEL_INNER: LevelFilter = LevelFilter::Trace;
1502     } else if #[cfg(feature = "max_level_off")] {
1503         const MAX_LEVEL_INNER: LevelFilter = LevelFilter::Off;
1504     } else if #[cfg(feature = "max_level_error")] {
1505         const MAX_LEVEL_INNER: LevelFilter = LevelFilter::Error;
1506     } else if #[cfg(feature = "max_level_warn")] {
1507         const MAX_LEVEL_INNER: LevelFilter = LevelFilter::Warn;
1508     } else if #[cfg(feature = "max_level_info")] {
1509         const MAX_LEVEL_INNER: LevelFilter = LevelFilter::Info;
1510     } else if #[cfg(feature = "max_level_debug")] {
1511         const MAX_LEVEL_INNER: LevelFilter = LevelFilter::Debug;
1512     } else {
1513         const MAX_LEVEL_INNER: LevelFilter = LevelFilter::Trace;
1514     }
1515 }
1516 
1517 #[cfg(test)]
1518 mod tests {
1519     extern crate std;
1520     use super::{Level, LevelFilter, ParseLevelError};
1521     use tests::std::string::ToString;
1522 
1523     #[test]
test_levelfilter_from_str()1524     fn test_levelfilter_from_str() {
1525         let tests = [
1526             ("off", Ok(LevelFilter::Off)),
1527             ("error", Ok(LevelFilter::Error)),
1528             ("warn", Ok(LevelFilter::Warn)),
1529             ("info", Ok(LevelFilter::Info)),
1530             ("debug", Ok(LevelFilter::Debug)),
1531             ("trace", Ok(LevelFilter::Trace)),
1532             ("OFF", Ok(LevelFilter::Off)),
1533             ("ERROR", Ok(LevelFilter::Error)),
1534             ("WARN", Ok(LevelFilter::Warn)),
1535             ("INFO", Ok(LevelFilter::Info)),
1536             ("DEBUG", Ok(LevelFilter::Debug)),
1537             ("TRACE", Ok(LevelFilter::Trace)),
1538             ("asdf", Err(ParseLevelError(()))),
1539         ];
1540         for &(s, ref expected) in &tests {
1541             assert_eq!(expected, &s.parse());
1542         }
1543     }
1544 
1545     #[test]
test_level_from_str()1546     fn test_level_from_str() {
1547         let tests = [
1548             ("OFF", Err(ParseLevelError(()))),
1549             ("error", Ok(Level::Error)),
1550             ("warn", Ok(Level::Warn)),
1551             ("info", Ok(Level::Info)),
1552             ("debug", Ok(Level::Debug)),
1553             ("trace", Ok(Level::Trace)),
1554             ("ERROR", Ok(Level::Error)),
1555             ("WARN", Ok(Level::Warn)),
1556             ("INFO", Ok(Level::Info)),
1557             ("DEBUG", Ok(Level::Debug)),
1558             ("TRACE", Ok(Level::Trace)),
1559             ("asdf", Err(ParseLevelError(()))),
1560         ];
1561         for &(s, ref expected) in &tests {
1562             assert_eq!(expected, &s.parse());
1563         }
1564     }
1565 
1566     #[test]
test_level_as_str()1567     fn test_level_as_str() {
1568         let tests = &[
1569             (Level::Error, "ERROR"),
1570             (Level::Warn, "WARN"),
1571             (Level::Info, "INFO"),
1572             (Level::Debug, "DEBUG"),
1573             (Level::Trace, "TRACE"),
1574         ];
1575         for (input, expected) in tests {
1576             assert_eq!(*expected, input.as_str());
1577         }
1578     }
1579 
1580     #[test]
test_level_show()1581     fn test_level_show() {
1582         assert_eq!("INFO", Level::Info.to_string());
1583         assert_eq!("ERROR", Level::Error.to_string());
1584     }
1585 
1586     #[test]
test_levelfilter_show()1587     fn test_levelfilter_show() {
1588         assert_eq!("OFF", LevelFilter::Off.to_string());
1589         assert_eq!("ERROR", LevelFilter::Error.to_string());
1590     }
1591 
1592     #[test]
test_cross_cmp()1593     fn test_cross_cmp() {
1594         assert!(Level::Debug > LevelFilter::Error);
1595         assert!(LevelFilter::Warn < Level::Trace);
1596         assert!(LevelFilter::Off < Level::Error);
1597     }
1598 
1599     #[test]
test_cross_eq()1600     fn test_cross_eq() {
1601         assert!(Level::Error == LevelFilter::Error);
1602         assert!(LevelFilter::Off != Level::Error);
1603         assert!(Level::Trace == LevelFilter::Trace);
1604     }
1605 
1606     #[test]
test_to_level()1607     fn test_to_level() {
1608         assert_eq!(Some(Level::Error), LevelFilter::Error.to_level());
1609         assert_eq!(None, LevelFilter::Off.to_level());
1610         assert_eq!(Some(Level::Debug), LevelFilter::Debug.to_level());
1611     }
1612 
1613     #[test]
test_to_level_filter()1614     fn test_to_level_filter() {
1615         assert_eq!(LevelFilter::Error, Level::Error.to_level_filter());
1616         assert_eq!(LevelFilter::Trace, Level::Trace.to_level_filter());
1617     }
1618 
1619     #[test]
test_level_filter_as_str()1620     fn test_level_filter_as_str() {
1621         let tests = &[
1622             (LevelFilter::Off, "OFF"),
1623             (LevelFilter::Error, "ERROR"),
1624             (LevelFilter::Warn, "WARN"),
1625             (LevelFilter::Info, "INFO"),
1626             (LevelFilter::Debug, "DEBUG"),
1627             (LevelFilter::Trace, "TRACE"),
1628         ];
1629         for (input, expected) in tests {
1630             assert_eq!(*expected, input.as_str());
1631         }
1632     }
1633 
1634     #[test]
1635     #[cfg(feature = "std")]
test_error_trait()1636     fn test_error_trait() {
1637         use super::SetLoggerError;
1638         let e = SetLoggerError(());
1639         assert_eq!(
1640             &e.to_string(),
1641             "attempted to set a logger after the logging system \
1642              was already initialized"
1643         );
1644     }
1645 
1646     #[test]
test_metadata_builder()1647     fn test_metadata_builder() {
1648         use super::MetadataBuilder;
1649         let target = "myApp";
1650         let metadata_test = MetadataBuilder::new()
1651             .level(Level::Debug)
1652             .target(target)
1653             .build();
1654         assert_eq!(metadata_test.level(), Level::Debug);
1655         assert_eq!(metadata_test.target(), "myApp");
1656     }
1657 
1658     #[test]
test_metadata_convenience_builder()1659     fn test_metadata_convenience_builder() {
1660         use super::Metadata;
1661         let target = "myApp";
1662         let metadata_test = Metadata::builder()
1663             .level(Level::Debug)
1664             .target(target)
1665             .build();
1666         assert_eq!(metadata_test.level(), Level::Debug);
1667         assert_eq!(metadata_test.target(), "myApp");
1668     }
1669 
1670     #[test]
test_record_builder()1671     fn test_record_builder() {
1672         use super::{MetadataBuilder, RecordBuilder};
1673         let target = "myApp";
1674         let metadata = MetadataBuilder::new().target(target).build();
1675         let fmt_args = format_args!("hello");
1676         let record_test = RecordBuilder::new()
1677             .args(fmt_args)
1678             .metadata(metadata)
1679             .module_path(Some("foo"))
1680             .file(Some("bar"))
1681             .line(Some(30))
1682             .build();
1683         assert_eq!(record_test.metadata().target(), "myApp");
1684         assert_eq!(record_test.module_path(), Some("foo"));
1685         assert_eq!(record_test.file(), Some("bar"));
1686         assert_eq!(record_test.line(), Some(30));
1687     }
1688 
1689     #[test]
test_record_convenience_builder()1690     fn test_record_convenience_builder() {
1691         use super::{Metadata, Record};
1692         let target = "myApp";
1693         let metadata = Metadata::builder().target(target).build();
1694         let fmt_args = format_args!("hello");
1695         let record_test = Record::builder()
1696             .args(fmt_args)
1697             .metadata(metadata)
1698             .module_path(Some("foo"))
1699             .file(Some("bar"))
1700             .line(Some(30))
1701             .build();
1702         assert_eq!(record_test.target(), "myApp");
1703         assert_eq!(record_test.module_path(), Some("foo"));
1704         assert_eq!(record_test.file(), Some("bar"));
1705         assert_eq!(record_test.line(), Some(30));
1706     }
1707 
1708     #[test]
test_record_complete_builder()1709     fn test_record_complete_builder() {
1710         use super::{Level, Record};
1711         let target = "myApp";
1712         let record_test = Record::builder()
1713             .module_path(Some("foo"))
1714             .file(Some("bar"))
1715             .line(Some(30))
1716             .target(target)
1717             .level(Level::Error)
1718             .build();
1719         assert_eq!(record_test.target(), "myApp");
1720         assert_eq!(record_test.level(), Level::Error);
1721         assert_eq!(record_test.module_path(), Some("foo"));
1722         assert_eq!(record_test.file(), Some("bar"));
1723         assert_eq!(record_test.line(), Some(30));
1724     }
1725 
1726     #[test]
1727     #[cfg(feature = "kv_unstable")]
test_record_key_values_builder()1728     fn test_record_key_values_builder() {
1729         use super::Record;
1730         use kv::{self, Visitor};
1731 
1732         struct TestVisitor {
1733             seen_pairs: usize,
1734         }
1735 
1736         impl<'kvs> Visitor<'kvs> for TestVisitor {
1737             fn visit_pair(
1738                 &mut self,
1739                 _: kv::Key<'kvs>,
1740                 _: kv::Value<'kvs>,
1741             ) -> Result<(), kv::Error> {
1742                 self.seen_pairs += 1;
1743                 Ok(())
1744             }
1745         }
1746 
1747         let kvs: &[(&str, i32)] = &[("a", 1), ("b", 2)];
1748         let record_test = Record::builder().key_values(&kvs).build();
1749 
1750         let mut visitor = TestVisitor { seen_pairs: 0 };
1751 
1752         record_test.key_values().visit(&mut visitor).unwrap();
1753 
1754         assert_eq!(2, visitor.seen_pairs);
1755     }
1756 
1757     #[test]
1758     #[cfg(feature = "kv_unstable")]
test_record_key_values_get_coerce()1759     fn test_record_key_values_get_coerce() {
1760         use super::Record;
1761 
1762         let kvs: &[(&str, &str)] = &[("a", "1"), ("b", "2")];
1763         let record = Record::builder().key_values(&kvs).build();
1764 
1765         assert_eq!(
1766             "2",
1767             record
1768                 .key_values()
1769                 .get("b".into())
1770                 .expect("missing key")
1771                 .to_borrowed_str()
1772                 .expect("invalid value")
1773         );
1774     }
1775 }
1776