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.
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.
11 //! A lightweight logging facade.
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.
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.
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.
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!`].
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
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.
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};
57 //! pub fn shave_the_yak(yak: &mut Yak) {
58 //! info!(target: "yak_events", "Commencing yak shaving for {:?}", yak);
61 //! match find_a_razor() {
63 //! info!("Razor located: {}", razor);
68 //! warn!("Unable to locate a razor: {}, retrying", err);
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.
83 //! The executable itself may use the `log` crate to log as well.
87 //! The logging system may only be initialized once.
89 //! ## Structured logging
91 //! If you enable the `kv_unstable` feature you can associate structured values
92 //! with your log records. If we take the example from before, we can include
93 //! some additional context besides what's in the formatted message:
96 //! # #[macro_use] extern crate serde;
97 //! # #[derive(Debug, Serialize)] pub struct Yak(String);
98 //! # impl Yak { fn shave(&mut self, _: u32) {} }
99 //! # fn find_a_razor() -> Result<u32, std::io::Error> { Ok(1) }
100 //! # #[cfg(feature = "kv_unstable_serde")]
102 //! use log::{info, warn, as_serde, as_error};
104 //! pub fn shave_the_yak(yak: &mut Yak) {
105 //! info!(target: "yak_events", yak = as_serde!(yak); "Commencing yak shaving");
108 //! match find_a_razor() {
110 //! info!(razor = razor; "Razor located");
111 //! yak.shave(razor);
115 //! warn!(err = as_error!(err); "Unable to locate a razor, retrying");
121 //! # #[cfg(not(feature = "kv_unstable_serde"))]
125 //! # Available logging implementations
127 //! In order to produce log output executables have to use
128 //! a logger implementation compatible with the facade.
129 //! There are many available implementations to choose from,
130 //! here are some of the most popular ones:
132 //! * Simple minimal loggers:
134 //! * [simple_logger]
136 //! * [pretty_env_logger]
139 //! * Complex configurable frameworks:
142 //! * Adaptors for other facilities:
145 //! * [systemd-journal-logger]
147 //! * [win_dbg_logger]
149 //! * For WebAssembly binaries:
151 //! * For dynamic libraries:
152 //! * You may need to construct an FFI-safe wrapper over `log` to initialize in your libraries
154 //! # Implementing a Logger
156 //! Loggers implement the [`Log`] trait. Here's a very basic example that simply
157 //! logs all messages at the [`Error`][level_link], [`Warn`][level_link] or
158 //! [`Info`][level_link] levels to stdout:
161 //! use log::{Record, Level, Metadata};
163 //! struct SimpleLogger;
165 //! impl log::Log for SimpleLogger {
166 //! fn enabled(&self, metadata: &Metadata) -> bool {
167 //! metadata.level() <= Level::Info
170 //! fn log(&self, record: &Record) {
171 //! if self.enabled(record.metadata()) {
172 //! println!("{} - {}", record.level(), record.args());
176 //! fn flush(&self) {}
182 //! Loggers are installed by calling the [`set_logger`] function. The maximum
183 //! log level also needs to be adjusted via the [`set_max_level`] function. The
184 //! logging facade uses this as an optimization to improve performance of log
185 //! messages at levels that are disabled. It's important to set it, as it
186 //! defaults to [`Off`][filter_link], so no log messages will ever be captured!
187 //! In the case of our example logger, we'll want to set the maximum log level
188 //! to [`Info`][filter_link], since we ignore any [`Debug`][level_link] or
189 //! [`Trace`][level_link] level log messages. A logging implementation should
190 //! provide a function that wraps a call to [`set_logger`] and
191 //! [`set_max_level`], handling initialization of the logger:
194 //! # use log::{Level, Metadata};
195 //! # struct SimpleLogger;
196 //! # impl log::Log for SimpleLogger {
197 //! # fn enabled(&self, _: &Metadata) -> bool { false }
198 //! # fn log(&self, _: &log::Record) {}
199 //! # fn flush(&self) {}
202 //! use log::{SetLoggerError, LevelFilter};
204 //! static LOGGER: SimpleLogger = SimpleLogger;
206 //! pub fn init() -> Result<(), SetLoggerError> {
207 //! log::set_logger(&LOGGER)
208 //! .map(|()| log::set_max_level(LevelFilter::Info))
212 //! Implementations that adjust their configurations at runtime should take care
213 //! to adjust the maximum log level as well.
217 //! `set_logger` requires you to provide a `&'static Log`, which can be hard to
218 //! obtain if your logger depends on some runtime configuration. The
219 //! `set_boxed_logger` function is available with the `std` Cargo feature. It is
220 //! identical to `set_logger` except that it takes a `Box<Log>` rather than a
224 //! # use log::{Level, LevelFilter, Log, SetLoggerError, Metadata};
225 //! # struct SimpleLogger;
226 //! # impl log::Log for SimpleLogger {
227 //! # fn enabled(&self, _: &Metadata) -> bool { false }
228 //! # fn log(&self, _: &log::Record) {}
229 //! # fn flush(&self) {}
232 //! # #[cfg(feature = "std")]
233 //! pub fn init() -> Result<(), SetLoggerError> {
234 //! log::set_boxed_logger(Box::new(SimpleLogger))
235 //! .map(|()| log::set_max_level(LevelFilter::Info))
239 //! # Compile time filters
241 //! Log levels can be statically disabled at compile time via Cargo features. Log invocations at
242 //! disabled levels will be skipped and will not even be present in the resulting binary.
243 //! This level is configured separately for release and debug builds. The features are:
245 //! * `max_level_off`
246 //! * `max_level_error`
247 //! * `max_level_warn`
248 //! * `max_level_info`
249 //! * `max_level_debug`
250 //! * `max_level_trace`
251 //! * `release_max_level_off`
252 //! * `release_max_level_error`
253 //! * `release_max_level_warn`
254 //! * `release_max_level_info`
255 //! * `release_max_level_debug`
256 //! * `release_max_level_trace`
258 //! These features control the value of the `STATIC_MAX_LEVEL` constant. The logging macros check
259 //! this value before logging a message. By default, no levels are disabled.
261 //! Libraries should avoid using the max level features because they're global and can't be changed
262 //! once they're set.
264 //! For example, a crate can disable trace level logs in debug builds and trace, debug, and info
265 //! level logs in release builds with the following configuration:
269 //! log = { version = "0.4", features = ["max_level_debug", "release_max_level_warn"] }
271 //! # Crate Feature Flags
273 //! The following crate feature flags are available in addition to the filters. They are
274 //! configured in your `Cargo.toml`.
276 //! * `std` allows use of `std` crate instead of the default `core`. Enables using `std::error` and
277 //! `set_boxed_logger` functionality.
278 //! * `serde` enables support for serialization and deserialization of `Level` and `LevelFilter`.
282 //! log = { version = "0.4", features = ["std", "serde"] }
285 //! # Version compatibility
287 //! The 0.3 and 0.4 versions of the `log` crate are almost entirely compatible. Log messages
288 //! made using `log` 0.3 will forward transparently to a logger implementation using `log` 0.4. Log
289 //! messages made using `log` 0.4 will forward to a logger implementation using `log` 0.3, but the
290 //! module path and file name information associated with the message will unfortunately be lost.
292 //! [`Log`]: trait.Log.html
293 //! [level_link]: enum.Level.html
294 //! [filter_link]: enum.LevelFilter.html
295 //! [`set_logger`]: fn.set_logger.html
296 //! [`set_max_level`]: fn.set_max_level.html
297 //! [`try_set_logger_raw`]: fn.try_set_logger_raw.html
298 //! [`shutdown_logger_raw`]: fn.shutdown_logger_raw.html
299 //! [env_logger]: https://docs.rs/env_logger/*/env_logger/
300 //! [simple_logger]: https://github.com/borntyping/rust-simple_logger
301 //! [simplelog]: https://github.com/drakulix/simplelog.rs
302 //! [pretty_env_logger]: https://docs.rs/pretty_env_logger/*/pretty_env_logger/
303 //! [stderrlog]: https://docs.rs/stderrlog/*/stderrlog/
304 //! [flexi_logger]: https://docs.rs/flexi_logger/*/flexi_logger/
305 //! [syslog]: https://docs.rs/syslog/*/syslog/
306 //! [slog-stdlog]: https://docs.rs/slog-stdlog/*/slog_stdlog/
307 //! [log4rs]: https://docs.rs/log4rs/*/log4rs/
308 //! [fern]: https://docs.rs/fern/*/fern/
309 //! [systemd-journal-logger]: https://docs.rs/systemd-journal-logger/*/systemd_journal_logger/
310 //! [android_log]: https://docs.rs/android_log/*/android_log/
311 //! [win_dbg_logger]: https://docs.rs/win_dbg_logger/*/win_dbg_logger/
312 //! [console_log]: https://docs.rs/console_log/*/console_log/
315 html_logo_url
= "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
316 html_favicon_url
= "https://www.rust-lang.org/favicon.ico",
317 html_root_url
= "https://docs.rs/log/0.4.17"
319 #![warn(missing_docs)]
320 #![deny(missing_debug_implementations, unconditional_recursion)]
321 #![cfg_attr(all(not(feature = "std"), not(test)), no_std)]
322 // When compiled for the rustc compiler itself we want to make sure that this is
324 #![cfg_attr(rustbuild, feature(staged_api, rustc_private))]
325 #![cfg_attr(rustbuild, unstable(feature = "rustc_private", issue = "27812"))]
327 #[cfg(all(not(feature = "std"), not(test)))]
328 extern crate core
as std
;
334 #[cfg(feature = "std")]
338 use std
::str::FromStr
;
344 #[cfg(feature = "kv_unstable")]
348 use std
::sync
::atomic
::{AtomicUsize, Ordering}
;
350 #[cfg(not(has_atomics))]
352 #[cfg(not(has_atomics))]
353 use std
::sync
::atomic
::Ordering
;
355 #[cfg(not(has_atomics))]
360 #[cfg(not(has_atomics))]
362 const fn new(v
: usize) -> AtomicUsize
{
363 AtomicUsize { v: Cell::new(v) }
366 fn load(&self, _order
: Ordering
) -> usize {
370 fn store(&self, val
: usize, _order
: Ordering
) {
381 ) -> Result
<usize, usize> {
382 let prev
= self.v
.get();
390 // Any platform without atomics is unlikely to have multiple cores, so
391 // writing via Cell will not be a race condition.
392 #[cfg(not(has_atomics))]
393 unsafe impl Sync
for AtomicUsize {}
395 // The LOGGER static holds a pointer to the global logger. It is protected by
396 // the STATE static which determines whether LOGGER has been initialized yet.
397 static mut LOGGER
: &dyn Log
= &NopLogger
;
399 static STATE
: AtomicUsize
= AtomicUsize
::new(0);
401 // There are three different states that we care about: the logger's
402 // uninitialized, the logger's initializing (set_logger's been called but
403 // LOGGER hasn't actually been set yet), or the logger's active.
404 const UNINITIALIZED
: usize = 0;
405 const INITIALIZING
: usize = 1;
406 const INITIALIZED
: usize = 2;
408 static MAX_LOG_LEVEL_FILTER
: AtomicUsize
= AtomicUsize
::new(0);
410 static LOG_LEVEL_NAMES
: [&str; 6] = ["OFF", "ERROR", "WARN", "INFO", "DEBUG", "TRACE"];
412 static SET_LOGGER_ERROR
: &str = "attempted to set a logger after the logging system \
413 was already initialized";
414 static LEVEL_PARSE_ERROR
: &str =
415 "attempted to convert a string that doesn't match an existing log level";
417 /// An enum representing the available verbosity levels of the logger.
419 /// Typical usage includes: checking if a certain `Level` is enabled with
420 /// [`log_enabled!`](macro.log_enabled.html), specifying the `Level` of
421 /// [`log!`](macro.log.html), and comparing a `Level` directly to a
422 /// [`LevelFilter`](enum.LevelFilter.html).
424 #[derive(Copy, Eq, Debug, Hash)]
426 /// The "error" level.
428 /// Designates very serious errors.
429 // This way these line up with the discriminants for LevelFilter below
430 // This works because Rust treats field-less enums the same way as C does:
431 // https://doc.rust-lang.org/reference/items/enumerations.html#custom-discriminant-values-for-field-less-enumerations
433 /// The "warn" level.
435 /// Designates hazardous situations.
437 /// The "info" level.
439 /// Designates useful information.
441 /// The "debug" level.
443 /// Designates lower priority information.
445 /// The "trace" level.
447 /// Designates very low priority, often extremely verbose, information.
451 impl Clone
for Level
{
453 fn clone(&self) -> Level
{
458 impl PartialEq
for Level
{
460 fn eq(&self, other
: &Level
) -> bool
{
461 *self as usize == *other
as usize
465 impl PartialEq
<LevelFilter
> for Level
{
467 fn eq(&self, other
: &LevelFilter
) -> bool
{
468 *self as usize == *other
as usize
472 impl PartialOrd
for Level
{
474 fn partial_cmp(&self, other
: &Level
) -> Option
<cmp
::Ordering
> {
475 Some(self.cmp(other
))
479 fn lt(&self, other
: &Level
) -> bool
{
480 (*self as usize) < *other
as usize
484 fn le(&self, other
: &Level
) -> bool
{
485 *self as usize <= *other
as usize
489 fn gt(&self, other
: &Level
) -> bool
{
490 *self as usize > *other
as usize
494 fn ge(&self, other
: &Level
) -> bool
{
495 *self as usize >= *other
as usize
499 impl PartialOrd
<LevelFilter
> for Level
{
501 fn partial_cmp(&self, other
: &LevelFilter
) -> Option
<cmp
::Ordering
> {
502 Some((*self as usize).cmp(&(*other
as usize)))
506 fn lt(&self, other
: &LevelFilter
) -> bool
{
507 (*self as usize) < *other
as usize
511 fn le(&self, other
: &LevelFilter
) -> bool
{
512 *self as usize <= *other
as usize
516 fn gt(&self, other
: &LevelFilter
) -> bool
{
517 *self as usize > *other
as usize
521 fn ge(&self, other
: &LevelFilter
) -> bool
{
522 *self as usize >= *other
as usize
528 fn cmp(&self, other
: &Level
) -> cmp
::Ordering
{
529 (*self as usize).cmp(&(*other
as usize))
533 fn ok_or
<T
, E
>(t
: Option
<T
>, e
: E
) -> Result
<T
, E
> {
540 // Reimplemented here because std::ascii is not available in libcore
541 fn eq_ignore_ascii_case(a
: &str, b
: &str) -> bool
{
542 fn to_ascii_uppercase(c
: u8) -> u8 {
543 if c
>= b'a'
&& c
<= b'z'
{
550 if a
.len() == b
.len() {
553 .all(|(a
, b
)| to_ascii_uppercase(a
) == to_ascii_uppercase(b
))
559 impl FromStr
for Level
{
560 type Err
= ParseLevelError
;
561 fn from_str(level
: &str) -> Result
<Level
, Self::Err
> {
565 .position(|&name
| eq_ignore_ascii_case(name
, level
))
567 .filter(|&idx
| idx
!= 0)
568 .map(|idx
| Level
::from_usize(idx
).unwrap())
575 impl fmt
::Display
for Level
{
576 fn fmt(&self, fmt
: &mut fmt
::Formatter
) -> fmt
::Result
{
577 fmt
.pad(self.as_str())
582 fn from_usize(u
: usize) -> Option
<Level
> {
584 1 => Some(Level
::Error
),
585 2 => Some(Level
::Warn
),
586 3 => Some(Level
::Info
),
587 4 => Some(Level
::Debug
),
588 5 => Some(Level
::Trace
),
593 /// Returns the most verbose logging level.
595 pub fn max() -> Level
{
599 /// Converts the `Level` to the equivalent `LevelFilter`.
601 pub fn to_level_filter(&self) -> LevelFilter
{
602 LevelFilter
::from_usize(*self as usize).unwrap()
605 /// Returns the string representation of the `Level`.
607 /// This returns the same string as the `fmt::Display` implementation.
608 pub fn as_str(&self) -> &'
static str {
609 LOG_LEVEL_NAMES
[*self as usize]
612 /// Iterate through all supported logging levels.
614 /// The order of iteration is from more severe to less severe log messages.
621 /// let mut levels = Level::iter();
623 /// assert_eq!(Some(Level::Error), levels.next());
624 /// assert_eq!(Some(Level::Trace), levels.last());
626 pub fn iter() -> impl Iterator
<Item
= Self> {
627 (1..6).map(|i
| Self::from_usize(i
).unwrap())
631 /// An enum representing the available verbosity level filters of the logger.
633 /// A `LevelFilter` may be compared directly to a [`Level`]. Use this type
634 /// to get and set the maximum log level with [`max_level()`] and [`set_max_level`].
636 /// [`Level`]: enum.Level.html
637 /// [`max_level()`]: fn.max_level.html
638 /// [`set_max_level`]: fn.set_max_level.html
640 #[derive(Copy, Eq, Debug, Hash)]
641 pub enum LevelFilter
{
642 /// A level lower than all log levels.
644 /// Corresponds to the `Error` log level.
646 /// Corresponds to the `Warn` log level.
648 /// Corresponds to the `Info` log level.
650 /// Corresponds to the `Debug` log level.
652 /// Corresponds to the `Trace` log level.
656 // Deriving generates terrible impls of these traits
658 impl Clone
for LevelFilter
{
660 fn clone(&self) -> LevelFilter
{
665 impl PartialEq
for LevelFilter
{
667 fn eq(&self, other
: &LevelFilter
) -> bool
{
668 *self as usize == *other
as usize
672 impl PartialEq
<Level
> for LevelFilter
{
674 fn eq(&self, other
: &Level
) -> bool
{
679 impl PartialOrd
for LevelFilter
{
681 fn partial_cmp(&self, other
: &LevelFilter
) -> Option
<cmp
::Ordering
> {
682 Some(self.cmp(other
))
686 fn lt(&self, other
: &LevelFilter
) -> bool
{
687 (*self as usize) < *other
as usize
691 fn le(&self, other
: &LevelFilter
) -> bool
{
692 *self as usize <= *other
as usize
696 fn gt(&self, other
: &LevelFilter
) -> bool
{
697 *self as usize > *other
as usize
701 fn ge(&self, other
: &LevelFilter
) -> bool
{
702 *self as usize >= *other
as usize
706 impl PartialOrd
<Level
> for LevelFilter
{
708 fn partial_cmp(&self, other
: &Level
) -> Option
<cmp
::Ordering
> {
709 Some((*self as usize).cmp(&(*other
as usize)))
713 fn lt(&self, other
: &Level
) -> bool
{
714 (*self as usize) < *other
as usize
718 fn le(&self, other
: &Level
) -> bool
{
719 *self as usize <= *other
as usize
723 fn gt(&self, other
: &Level
) -> bool
{
724 *self as usize > *other
as usize
728 fn ge(&self, other
: &Level
) -> bool
{
729 *self as usize >= *other
as usize
733 impl Ord
for LevelFilter
{
735 fn cmp(&self, other
: &LevelFilter
) -> cmp
::Ordering
{
736 (*self as usize).cmp(&(*other
as usize))
740 impl FromStr
for LevelFilter
{
741 type Err
= ParseLevelError
;
742 fn from_str(level
: &str) -> Result
<LevelFilter
, Self::Err
> {
746 .position(|&name
| eq_ignore_ascii_case(name
, level
))
747 .map(|p
| LevelFilter
::from_usize(p
).unwrap()),
753 impl fmt
::Display
for LevelFilter
{
754 fn fmt(&self, fmt
: &mut fmt
::Formatter
) -> fmt
::Result
{
755 fmt
.pad(self.as_str())
760 fn from_usize(u
: usize) -> Option
<LevelFilter
> {
762 0 => Some(LevelFilter
::Off
),
763 1 => Some(LevelFilter
::Error
),
764 2 => Some(LevelFilter
::Warn
),
765 3 => Some(LevelFilter
::Info
),
766 4 => Some(LevelFilter
::Debug
),
767 5 => Some(LevelFilter
::Trace
),
772 /// Returns the most verbose logging level filter.
774 pub fn max() -> LevelFilter
{
778 /// Converts `self` to the equivalent `Level`.
780 /// Returns `None` if `self` is `LevelFilter::Off`.
782 pub fn to_level(&self) -> Option
<Level
> {
783 Level
::from_usize(*self as usize)
786 /// Returns the string representation of the `LevelFilter`.
788 /// This returns the same string as the `fmt::Display` implementation.
789 pub fn as_str(&self) -> &'
static str {
790 LOG_LEVEL_NAMES
[*self as usize]
793 /// Iterate through all supported filtering levels.
795 /// The order of iteration is from less to more verbose filtering.
800 /// use log::LevelFilter;
802 /// let mut levels = LevelFilter::iter();
804 /// assert_eq!(Some(LevelFilter::Off), levels.next());
805 /// assert_eq!(Some(LevelFilter::Trace), levels.last());
807 pub fn iter() -> impl Iterator
<Item
= Self> {
808 (0..6).map(|i
| Self::from_usize(i
).unwrap())
812 #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
813 enum MaybeStaticStr
<'a
> {
814 Static(&'
static str),
818 impl<'a
> MaybeStaticStr
<'a
> {
820 fn get(&self) -> &'a
str {
822 MaybeStaticStr
::Static(s
) => s
,
823 MaybeStaticStr
::Borrowed(s
) => s
,
828 /// The "payload" of a log message.
832 /// `Record` structures are passed as parameters to the [`log`][method.log]
833 /// method of the [`Log`] trait. Logger implementors manipulate these
834 /// structures in order to display log messages. `Record`s are automatically
835 /// created by the [`log!`] macro and so are not seen by log users.
837 /// Note that the [`level()`] and [`target()`] accessors are equivalent to
838 /// `self.metadata().level()` and `self.metadata().target()` respectively.
839 /// These methods are provided as a convenience for users of this structure.
843 /// The following example shows a simple logger that displays the level,
844 /// module path, and message of any `Record` that is passed to it.
847 /// struct SimpleLogger;
849 /// impl log::Log for SimpleLogger {
850 /// fn enabled(&self, metadata: &log::Metadata) -> bool {
854 /// fn log(&self, record: &log::Record) {
855 /// if !self.enabled(record.metadata()) {
859 /// println!("{}:{} -- {}",
864 /// fn flush(&self) {}
868 /// [method.log]: trait.Log.html#tymethod.log
869 /// [`Log`]: trait.Log.html
870 /// [`log!`]: macro.log.html
871 /// [`level()`]: struct.Record.html#method.level
872 /// [`target()`]: struct.Record.html#method.target
873 #[derive(Clone, Debug)]
874 pub struct Record
<'a
> {
875 metadata
: Metadata
<'a
>,
876 args
: fmt
::Arguments
<'a
>,
877 module_path
: Option
<MaybeStaticStr
<'a
>>,
878 file
: Option
<MaybeStaticStr
<'a
>>,
880 #[cfg(feature = "kv_unstable")]
881 key_values
: KeyValues
<'a
>,
884 // This wrapper type is only needed so we can
885 // `#[derive(Debug)]` on `Record`. It also
886 // provides a useful `Debug` implementation for
887 // the underlying `Source`.
888 #[cfg(feature = "kv_unstable")]
890 struct KeyValues
<'a
>(&'a
dyn kv
::Source
);
892 #[cfg(feature = "kv_unstable")]
893 impl<'a
> fmt
::Debug
for KeyValues
<'a
> {
894 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
895 let mut visitor
= f
.debug_map();
896 self.0.visit(&mut visitor
).map_err(|_
| fmt
::Error
)?
;
901 impl<'a
> Record
<'a
> {
902 /// Returns a new builder.
904 pub fn builder() -> RecordBuilder
<'a
> {
908 /// The message body.
910 pub fn args(&self) -> &fmt
::Arguments
<'a
> {
914 /// Metadata about the log directive.
916 pub fn metadata(&self) -> &Metadata
<'a
> {
920 /// The verbosity level of the message.
922 pub fn level(&self) -> Level
{
923 self.metadata
.level()
926 /// The name of the target of the directive.
928 pub fn target(&self) -> &'a
str {
929 self.metadata
.target()
932 /// The module path of the message.
934 pub fn module_path(&self) -> Option
<&'a
str> {
935 self.module_path
.map(|s
| s
.get())
938 /// The module path of the message, if it is a `'static` string.
940 pub fn module_path_static(&self) -> Option
<&'
static str> {
941 match self.module_path
{
942 Some(MaybeStaticStr
::Static(s
)) => Some(s
),
947 /// The source file containing the message.
949 pub fn file(&self) -> Option
<&'a
str> {
950 self.file
.map(|s
| s
.get())
953 /// The module path of the message, if it is a `'static` string.
955 pub fn file_static(&self) -> Option
<&'
static str> {
957 Some(MaybeStaticStr
::Static(s
)) => Some(s
),
962 /// The line containing the message.
964 pub fn line(&self) -> Option
<u32> {
968 /// The structured key-value pairs associated with the message.
969 #[cfg(feature = "kv_unstable")]
971 pub fn key_values(&self) -> &dyn kv
::Source
{
975 /// Create a new [`RecordBuilder`](struct.RecordBuilder.html) based on this record.
976 #[cfg(feature = "kv_unstable")]
978 pub fn to_builder(&self) -> RecordBuilder
{
982 level
: self.metadata
.level
,
983 target
: self.metadata
.target
,
986 module_path
: self.module_path
,
989 key_values
: self.key_values
.clone(),
995 /// Builder for [`Record`](struct.Record.html).
997 /// Typically should only be used by log library creators or for testing and "shim loggers".
998 /// The `RecordBuilder` can set the different parameters of `Record` object, and returns
999 /// the created object when `build` is called.
1004 /// use log::{Level, Record};
1006 /// let record = Record::builder()
1007 /// .args(format_args!("Error!"))
1008 /// .level(Level::Error)
1009 /// .target("myApp")
1010 /// .file(Some("server.rs"))
1011 /// .line(Some(144))
1012 /// .module_path(Some("server"))
1016 /// Alternatively, use [`MetadataBuilder`](struct.MetadataBuilder.html):
1019 /// use log::{Record, Level, MetadataBuilder};
1021 /// let error_metadata = MetadataBuilder::new()
1022 /// .target("myApp")
1023 /// .level(Level::Error)
1026 /// let record = Record::builder()
1027 /// .metadata(error_metadata)
1028 /// .args(format_args!("Error!"))
1029 /// .line(Some(433))
1030 /// .file(Some("app.rs"))
1031 /// .module_path(Some("server"))
1035 pub struct RecordBuilder
<'a
> {
1039 impl<'a
> RecordBuilder
<'a
> {
1040 /// Construct new `RecordBuilder`.
1042 /// The default options are:
1044 /// - `args`: [`format_args!("")`]
1045 /// - `metadata`: [`Metadata::builder().build()`]
1046 /// - `module_path`: `None`
1047 /// - `file`: `None`
1048 /// - `line`: `None`
1050 /// [`format_args!("")`]: https://doc.rust-lang.org/std/macro.format_args.html
1051 /// [`Metadata::builder().build()`]: struct.MetadataBuilder.html#method.build
1053 pub fn new() -> RecordBuilder
<'a
> {
1056 args
: format_args
!(""),
1057 metadata
: Metadata
::builder().build(),
1061 #[cfg(feature = "kv_unstable")]
1062 key_values
: KeyValues(&Option
::None
::<(kv
::Key
, kv
::Value
)>),
1067 /// Set [`args`](struct.Record.html#method.args).
1069 pub fn args(&mut self, args
: fmt
::Arguments
<'a
>) -> &mut RecordBuilder
<'a
> {
1070 self.record
.args
= args
;
1074 /// Set [`metadata`](struct.Record.html#method.metadata). Construct a `Metadata` object with [`MetadataBuilder`](struct.MetadataBuilder.html).
1076 pub fn metadata(&mut self, metadata
: Metadata
<'a
>) -> &mut RecordBuilder
<'a
> {
1077 self.record
.metadata
= metadata
;
1081 /// Set [`Metadata::level`](struct.Metadata.html#method.level).
1083 pub fn level(&mut self, level
: Level
) -> &mut RecordBuilder
<'a
> {
1084 self.record
.metadata
.level
= level
;
1088 /// Set [`Metadata::target`](struct.Metadata.html#method.target)
1090 pub fn target(&mut self, target
: &'a
str) -> &mut RecordBuilder
<'a
> {
1091 self.record
.metadata
.target
= target
;
1095 /// Set [`module_path`](struct.Record.html#method.module_path)
1097 pub fn module_path(&mut self, path
: Option
<&'a
str>) -> &mut RecordBuilder
<'a
> {
1098 self.record
.module_path
= path
.map(MaybeStaticStr
::Borrowed
);
1102 /// Set [`module_path`](struct.Record.html#method.module_path) to a `'static` string
1104 pub fn module_path_static(&mut self, path
: Option
<&'
static str>) -> &mut RecordBuilder
<'a
> {
1105 self.record
.module_path
= path
.map(MaybeStaticStr
::Static
);
1109 /// Set [`file`](struct.Record.html#method.file)
1111 pub fn file(&mut self, file
: Option
<&'a
str>) -> &mut RecordBuilder
<'a
> {
1112 self.record
.file
= file
.map(MaybeStaticStr
::Borrowed
);
1116 /// Set [`file`](struct.Record.html#method.file) to a `'static` string.
1118 pub fn file_static(&mut self, file
: Option
<&'
static str>) -> &mut RecordBuilder
<'a
> {
1119 self.record
.file
= file
.map(MaybeStaticStr
::Static
);
1123 /// Set [`line`](struct.Record.html#method.line)
1125 pub fn line(&mut self, line
: Option
<u32>) -> &mut RecordBuilder
<'a
> {
1126 self.record
.line
= line
;
1130 /// Set [`key_values`](struct.Record.html#method.key_values)
1131 #[cfg(feature = "kv_unstable")]
1133 pub fn key_values(&mut self, kvs
: &'a
dyn kv
::Source
) -> &mut RecordBuilder
<'a
> {
1134 self.record
.key_values
= KeyValues(kvs
);
1138 /// Invoke the builder and return a `Record`
1140 pub fn build(&self) -> Record
<'a
> {
1145 /// Metadata about a log message.
1149 /// `Metadata` structs are created when users of the library use
1152 /// They are consumed by implementations of the `Log` trait in the
1153 /// `enabled` method.
1155 /// `Record`s use `Metadata` to determine the log message's severity
1158 /// Users should use the `log_enabled!` macro in their code to avoid
1159 /// constructing expensive log messages.
1164 /// use log::{Record, Level, Metadata};
1166 /// struct MyLogger;
1168 /// impl log::Log for MyLogger {
1169 /// fn enabled(&self, metadata: &Metadata) -> bool {
1170 /// metadata.level() <= Level::Info
1173 /// fn log(&self, record: &Record) {
1174 /// if self.enabled(record.metadata()) {
1175 /// println!("{} - {}", record.level(), record.args());
1178 /// fn flush(&self) {}
1183 #[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
1184 pub struct Metadata
<'a
> {
1189 impl<'a
> Metadata
<'a
> {
1190 /// Returns a new builder.
1192 pub fn builder() -> MetadataBuilder
<'a
> {
1193 MetadataBuilder
::new()
1196 /// The verbosity level of the message.
1198 pub fn level(&self) -> Level
{
1202 /// The name of the target of the directive.
1204 pub fn target(&self) -> &'a
str {
1209 /// Builder for [`Metadata`](struct.Metadata.html).
1211 /// Typically should only be used by log library creators or for testing and "shim loggers".
1212 /// The `MetadataBuilder` can set the different parameters of a `Metadata` object, and returns
1213 /// the created object when `build` is called.
1218 /// let target = "myApp";
1219 /// use log::{Level, MetadataBuilder};
1220 /// let metadata = MetadataBuilder::new()
1221 /// .level(Level::Debug)
1225 #[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
1226 pub struct MetadataBuilder
<'a
> {
1227 metadata
: Metadata
<'a
>,
1230 impl<'a
> MetadataBuilder
<'a
> {
1231 /// Construct a new `MetadataBuilder`.
1233 /// The default options are:
1235 /// - `level`: `Level::Info`
1236 /// - `target`: `""`
1238 pub fn new() -> MetadataBuilder
<'a
> {
1240 metadata
: Metadata
{
1247 /// Setter for [`level`](struct.Metadata.html#method.level).
1249 pub fn level(&mut self, arg
: Level
) -> &mut MetadataBuilder
<'a
> {
1250 self.metadata
.level
= arg
;
1254 /// Setter for [`target`](struct.Metadata.html#method.target).
1256 pub fn target(&mut self, target
: &'a
str) -> &mut MetadataBuilder
<'a
> {
1257 self.metadata
.target
= target
;
1261 /// Returns a `Metadata` object.
1263 pub fn build(&self) -> Metadata
<'a
> {
1264 self.metadata
.clone()
1268 /// A trait encapsulating the operations required of a logger.
1269 pub trait Log
: Sync
+ Send
{
1270 /// Determines if a log message with the specified metadata would be
1273 /// This is used by the `log_enabled!` macro to allow callers to avoid
1274 /// expensive computation of log message arguments if the message would be
1275 /// discarded anyway.
1277 /// # For implementors
1279 /// This method isn't called automatically by the `log!` macros.
1280 /// It's up to an implementation of the `Log` trait to call `enabled` in its own
1281 /// `log` method implementation to guarantee that filtering is applied.
1282 fn enabled(&self, metadata
: &Metadata
) -> bool
;
1284 /// Logs the `Record`.
1286 /// # For implementors
1288 /// Note that `enabled` is *not* necessarily called before this method.
1289 /// Implementations of `log` should perform all necessary filtering
1291 fn log(&self, record
: &Record
);
1293 /// Flushes any buffered records.
1297 // Just used as a dummy initial value for LOGGER
1300 impl Log
for NopLogger
{
1301 fn enabled(&self, _
: &Metadata
) -> bool
{
1305 fn log(&self, _
: &Record
) {}
1309 impl<T
> Log
for &'_ T
1313 fn enabled(&self, metadata
: &Metadata
) -> bool
{
1314 (**self).enabled(metadata
)
1317 fn log(&self, record
: &Record
) {
1318 (**self).log(record
)
1325 #[cfg(feature = "std")]
1326 impl<T
> Log
for std
::boxed
::Box
<T
>
1330 fn enabled(&self, metadata
: &Metadata
) -> bool
{
1331 self.as_ref().enabled(metadata
)
1334 fn log(&self, record
: &Record
) {
1335 self.as_ref().log(record
)
1338 self.as_ref().flush()
1342 #[cfg(feature = "std")]
1343 impl<T
> Log
for std
::sync
::Arc
<T
>
1347 fn enabled(&self, metadata
: &Metadata
) -> bool
{
1348 self.as_ref().enabled(metadata
)
1351 fn log(&self, record
: &Record
) {
1352 self.as_ref().log(record
)
1355 self.as_ref().flush()
1359 /// Sets the global maximum log level.
1361 /// Generally, this should only be called by the active logging implementation.
1363 /// Note that `Trace` is the maximum level, because it provides the maximum amount of detail in the emitted logs.
1365 pub fn set_max_level(level
: LevelFilter
) {
1366 MAX_LOG_LEVEL_FILTER
.store(level
as usize, Ordering
::Relaxed
)
1369 /// Returns the current maximum log level.
1371 /// The [`log!`], [`error!`], [`warn!`], [`info!`], [`debug!`], and [`trace!`] macros check
1372 /// this value and discard any message logged at a higher level. The maximum
1373 /// log level is set by the [`set_max_level`] function.
1375 /// [`log!`]: macro.log.html
1376 /// [`error!`]: macro.error.html
1377 /// [`warn!`]: macro.warn.html
1378 /// [`info!`]: macro.info.html
1379 /// [`debug!`]: macro.debug.html
1380 /// [`trace!`]: macro.trace.html
1381 /// [`set_max_level`]: fn.set_max_level.html
1383 pub fn max_level() -> LevelFilter
{
1384 // Since `LevelFilter` is `repr(usize)`,
1385 // this transmute is sound if and only if `MAX_LOG_LEVEL_FILTER`
1386 // is set to a usize that is a valid discriminant for `LevelFilter`.
1387 // Since `MAX_LOG_LEVEL_FILTER` is private, the only time it's set
1388 // is by `set_max_level` above, i.e. by casting a `LevelFilter` to `usize`.
1389 // So any usize stored in `MAX_LOG_LEVEL_FILTER` is a valid discriminant.
1390 unsafe { mem::transmute(MAX_LOG_LEVEL_FILTER.load(Ordering::Relaxed)) }
1393 /// Sets the global logger to a `Box<Log>`.
1395 /// This is a simple convenience wrapper over `set_logger`, which takes a
1396 /// `Box<Log>` rather than a `&'static Log`. See the documentation for
1397 /// [`set_logger`] for more details.
1399 /// Requires the `std` feature.
1403 /// An error is returned if a logger has already been set.
1405 /// [`set_logger`]: fn.set_logger.html
1406 #[cfg(all(feature = "std", atomic_cas))]
1407 pub fn set_boxed_logger(logger
: Box
<dyn Log
>) -> Result
<(), SetLoggerError
> {
1408 set_logger_inner(|| Box
::leak(logger
))
1411 /// Sets the global logger to a `&'static Log`.
1413 /// This function may only be called once in the lifetime of a program. Any log
1414 /// events that occur before the call to `set_logger` completes will be ignored.
1416 /// This function does not typically need to be called manually. Logger
1417 /// implementations should provide an initialization method that installs the
1418 /// logger internally.
1422 /// This method is available even when the `std` feature is disabled. However,
1423 /// it is currently unavailable on `thumbv6` targets, which lack support for
1424 /// some atomic operations which are used by this function. Even on those
1425 /// targets, [`set_logger_racy`] will be available.
1429 /// An error is returned if a logger has already been set.
1434 /// use log::{error, info, warn, Record, Level, Metadata, LevelFilter};
1436 /// static MY_LOGGER: MyLogger = MyLogger;
1438 /// struct MyLogger;
1440 /// impl log::Log for MyLogger {
1441 /// fn enabled(&self, metadata: &Metadata) -> bool {
1442 /// metadata.level() <= Level::Info
1445 /// fn log(&self, record: &Record) {
1446 /// if self.enabled(record.metadata()) {
1447 /// println!("{} - {}", record.level(), record.args());
1450 /// fn flush(&self) {}
1454 /// log::set_logger(&MY_LOGGER).unwrap();
1455 /// log::set_max_level(LevelFilter::Info);
1457 /// info!("hello log");
1458 /// warn!("warning");
1463 /// [`set_logger_racy`]: fn.set_logger_racy.html
1465 pub fn set_logger(logger
: &'
static dyn Log
) -> Result
<(), SetLoggerError
> {
1466 set_logger_inner(|| logger
)
1470 fn set_logger_inner
<F
>(make_logger
: F
) -> Result
<(), SetLoggerError
>
1472 F
: FnOnce() -> &'
static dyn Log
,
1474 let old_state
= match STATE
.compare_exchange(
1480 Ok(s
) | Err(s
) => s
,
1485 LOGGER
= make_logger();
1487 STATE
.store(INITIALIZED
, Ordering
::SeqCst
);
1491 while STATE
.load(Ordering
::SeqCst
) == INITIALIZING
{
1492 // TODO: replace with `hint::spin_loop` once MSRV is 1.49.0.
1493 #[allow(deprecated)]
1494 std
::sync
::atomic
::spin_loop_hint();
1496 Err(SetLoggerError(()))
1498 _
=> Err(SetLoggerError(())),
1502 /// A thread-unsafe version of [`set_logger`].
1504 /// This function is available on all platforms, even those that do not have
1505 /// support for atomics that is needed by [`set_logger`].
1507 /// In almost all cases, [`set_logger`] should be preferred.
1511 /// This function is only safe to call when no other logger initialization
1512 /// function is called while this function still executes.
1514 /// This can be upheld by (for example) making sure that **there are no other
1515 /// threads**, and (on embedded) that **interrupts are disabled**.
1517 /// It is safe to use other logging functions while this function runs
1518 /// (including all logging macros).
1520 /// [`set_logger`]: fn.set_logger.html
1521 pub unsafe fn set_logger_racy(logger
: &'
static dyn Log
) -> Result
<(), SetLoggerError
> {
1522 match STATE
.load(Ordering
::SeqCst
) {
1525 STATE
.store(INITIALIZED
, Ordering
::SeqCst
);
1529 // This is just plain UB, since we were racing another initialization function
1530 unreachable
!("set_logger_racy must not be used with other initialization functions")
1532 _
=> Err(SetLoggerError(())),
1536 /// The type returned by [`set_logger`] if [`set_logger`] has already been called.
1538 /// [`set_logger`]: fn.set_logger.html
1539 #[allow(missing_copy_implementations)]
1541 pub struct SetLoggerError(());
1543 impl fmt
::Display
for SetLoggerError
{
1544 fn fmt(&self, fmt
: &mut fmt
::Formatter
) -> fmt
::Result
{
1545 fmt
.write_str(SET_LOGGER_ERROR
)
1549 // The Error trait is not available in libcore
1550 #[cfg(feature = "std")]
1551 impl error
::Error
for SetLoggerError {}
1553 /// The type returned by [`from_str`] when the string doesn't match any of the log levels.
1555 /// [`from_str`]: https://doc.rust-lang.org/std/str/trait.FromStr.html#tymethod.from_str
1556 #[allow(missing_copy_implementations)]
1557 #[derive(Debug, PartialEq)]
1558 pub struct ParseLevelError(());
1560 impl fmt
::Display
for ParseLevelError
{
1561 fn fmt(&self, fmt
: &mut fmt
::Formatter
) -> fmt
::Result
{
1562 fmt
.write_str(LEVEL_PARSE_ERROR
)
1566 // The Error trait is not available in libcore
1567 #[cfg(feature = "std")]
1568 impl error
::Error
for ParseLevelError {}
1570 /// Returns a reference to the logger.
1572 /// If a logger has not been set, a no-op implementation is returned.
1573 pub fn logger() -> &'
static dyn Log
{
1574 if STATE
.load(Ordering
::SeqCst
) != INITIALIZED
{
1575 static NOP
: NopLogger
= NopLogger
;
1582 // WARNING: this is not part of the crate's public API and is subject to change at any time
1584 #[cfg(not(feature = "kv_unstable"))]
1585 pub fn __private_api_log(
1586 args
: fmt
::Arguments
,
1588 &(target
, module_path
, file
, line
): &(&str, &'
static str, &'
static str, u32),
1589 kvs
: Option
<&[(&str, &str)]>,
1593 "key-value support is experimental and must be enabled using the `kv_unstable` feature"
1602 .module_path_static(Some(module_path
))
1603 .file_static(Some(file
))
1609 // WARNING: this is not part of the crate's public API and is subject to change at any time
1611 #[cfg(feature = "kv_unstable")]
1612 pub fn __private_api_log(
1613 args
: fmt
::Arguments
,
1615 &(target
, module_path
, file
, line
): &(&str, &'
static str, &'
static str, u32),
1616 kvs
: Option
<&[(&str, &dyn kv
::ToValue
)]>,
1623 .module_path_static(Some(module_path
))
1624 .file_static(Some(file
))
1631 // WARNING: this is not part of the crate's public API and is subject to change at any time
1633 pub fn __private_api_enabled(level
: Level
, target
: &str) -> bool
{
1634 logger().enabled(&Metadata
::builder().level(level
).target(target
).build())
1637 // WARNING: this is not part of the crate's public API and is subject to change at any time
1639 pub mod __private_api
{
1640 pub use std
::option
::Option
;
1643 /// The statically resolved maximum log level.
1645 /// See the crate level documentation for information on how to configure this.
1647 /// This value is checked by the log macros, but not by the `Log`ger returned by
1648 /// the [`logger`] function. Code that manually calls functions on that value
1649 /// should compare the level against this value.
1651 /// [`logger`]: fn.logger.html
1652 pub const STATIC_MAX_LEVEL
: LevelFilter
= MAX_LEVEL_INNER
;
1655 if #[cfg(all(not(debug_assertions), feature = "release_max_level_off"))] {
1656 const MAX_LEVEL_INNER
: LevelFilter
= LevelFilter
::Off
;
1657 } else if #[cfg(all(not(debug_assertions), feature = "release_max_level_error"))] {
1658 const MAX_LEVEL_INNER
: LevelFilter
= LevelFilter
::Error
;
1659 } else if #[cfg(all(not(debug_assertions), feature = "release_max_level_warn"))] {
1660 const MAX_LEVEL_INNER
: LevelFilter
= LevelFilter
::Warn
;
1661 } else if #[cfg(all(not(debug_assertions), feature = "release_max_level_info"))] {
1662 const MAX_LEVEL_INNER
: LevelFilter
= LevelFilter
::Info
;
1663 } else if #[cfg(all(not(debug_assertions), feature = "release_max_level_debug"))] {
1664 const MAX_LEVEL_INNER
: LevelFilter
= LevelFilter
::Debug
;
1665 } else if #[cfg(all(not(debug_assertions), feature = "release_max_level_trace"))] {
1666 const MAX_LEVEL_INNER
: LevelFilter
= LevelFilter
::Trace
;
1667 } else if #[cfg(feature = "max_level_off")] {
1668 const MAX_LEVEL_INNER
: LevelFilter
= LevelFilter
::Off
;
1669 } else if #[cfg(feature = "max_level_error")] {
1670 const MAX_LEVEL_INNER
: LevelFilter
= LevelFilter
::Error
;
1671 } else if #[cfg(feature = "max_level_warn")] {
1672 const MAX_LEVEL_INNER
: LevelFilter
= LevelFilter
::Warn
;
1673 } else if #[cfg(feature = "max_level_info")] {
1674 const MAX_LEVEL_INNER
: LevelFilter
= LevelFilter
::Info
;
1675 } else if #[cfg(feature = "max_level_debug")] {
1676 const MAX_LEVEL_INNER
: LevelFilter
= LevelFilter
::Debug
;
1678 const MAX_LEVEL_INNER
: LevelFilter
= LevelFilter
::Trace
;
1685 use super::{Level, LevelFilter, ParseLevelError}
;
1686 use tests
::std
::string
::ToString
;
1689 fn test_levelfilter_from_str() {
1691 ("off", Ok(LevelFilter
::Off
)),
1692 ("error", Ok(LevelFilter
::Error
)),
1693 ("warn", Ok(LevelFilter
::Warn
)),
1694 ("info", Ok(LevelFilter
::Info
)),
1695 ("debug", Ok(LevelFilter
::Debug
)),
1696 ("trace", Ok(LevelFilter
::Trace
)),
1697 ("OFF", Ok(LevelFilter
::Off
)),
1698 ("ERROR", Ok(LevelFilter
::Error
)),
1699 ("WARN", Ok(LevelFilter
::Warn
)),
1700 ("INFO", Ok(LevelFilter
::Info
)),
1701 ("DEBUG", Ok(LevelFilter
::Debug
)),
1702 ("TRACE", Ok(LevelFilter
::Trace
)),
1703 ("asdf", Err(ParseLevelError(()))),
1705 for &(s
, ref expected
) in &tests
{
1706 assert_eq
!(expected
, &s
.parse());
1711 fn test_level_from_str() {
1713 ("OFF", Err(ParseLevelError(()))),
1714 ("error", Ok(Level
::Error
)),
1715 ("warn", Ok(Level
::Warn
)),
1716 ("info", Ok(Level
::Info
)),
1717 ("debug", Ok(Level
::Debug
)),
1718 ("trace", Ok(Level
::Trace
)),
1719 ("ERROR", Ok(Level
::Error
)),
1720 ("WARN", Ok(Level
::Warn
)),
1721 ("INFO", Ok(Level
::Info
)),
1722 ("DEBUG", Ok(Level
::Debug
)),
1723 ("TRACE", Ok(Level
::Trace
)),
1724 ("asdf", Err(ParseLevelError(()))),
1726 for &(s
, ref expected
) in &tests
{
1727 assert_eq
!(expected
, &s
.parse());
1732 fn test_level_as_str() {
1734 (Level
::Error
, "ERROR"),
1735 (Level
::Warn
, "WARN"),
1736 (Level
::Info
, "INFO"),
1737 (Level
::Debug
, "DEBUG"),
1738 (Level
::Trace
, "TRACE"),
1740 for (input
, expected
) in tests
{
1741 assert_eq
!(*expected
, input
.as_str());
1746 fn test_level_show() {
1747 assert_eq
!("INFO", Level
::Info
.to_string());
1748 assert_eq
!("ERROR", Level
::Error
.to_string());
1752 fn test_levelfilter_show() {
1753 assert_eq
!("OFF", LevelFilter
::Off
.to_string());
1754 assert_eq
!("ERROR", LevelFilter
::Error
.to_string());
1758 fn test_cross_cmp() {
1759 assert
!(Level
::Debug
> LevelFilter
::Error
);
1760 assert
!(LevelFilter
::Warn
< Level
::Trace
);
1761 assert
!(LevelFilter
::Off
< Level
::Error
);
1765 fn test_cross_eq() {
1766 assert
!(Level
::Error
== LevelFilter
::Error
);
1767 assert
!(LevelFilter
::Off
!= Level
::Error
);
1768 assert
!(Level
::Trace
== LevelFilter
::Trace
);
1772 fn test_to_level() {
1773 assert_eq
!(Some(Level
::Error
), LevelFilter
::Error
.to_level());
1774 assert_eq
!(None
, LevelFilter
::Off
.to_level());
1775 assert_eq
!(Some(Level
::Debug
), LevelFilter
::Debug
.to_level());
1779 fn test_to_level_filter() {
1780 assert_eq
!(LevelFilter
::Error
, Level
::Error
.to_level_filter());
1781 assert_eq
!(LevelFilter
::Trace
, Level
::Trace
.to_level_filter());
1785 fn test_level_filter_as_str() {
1787 (LevelFilter
::Off
, "OFF"),
1788 (LevelFilter
::Error
, "ERROR"),
1789 (LevelFilter
::Warn
, "WARN"),
1790 (LevelFilter
::Info
, "INFO"),
1791 (LevelFilter
::Debug
, "DEBUG"),
1792 (LevelFilter
::Trace
, "TRACE"),
1794 for (input
, expected
) in tests
{
1795 assert_eq
!(*expected
, input
.as_str());
1800 #[cfg(feature = "std")]
1801 fn test_error_trait() {
1802 use super::SetLoggerError
;
1803 let e
= SetLoggerError(());
1806 "attempted to set a logger after the logging system \
1807 was already initialized"
1812 fn test_metadata_builder() {
1813 use super::MetadataBuilder
;
1814 let target
= "myApp";
1815 let metadata_test
= MetadataBuilder
::new()
1816 .level(Level
::Debug
)
1819 assert_eq
!(metadata_test
.level(), Level
::Debug
);
1820 assert_eq
!(metadata_test
.target(), "myApp");
1824 fn test_metadata_convenience_builder() {
1825 use super::Metadata
;
1826 let target
= "myApp";
1827 let metadata_test
= Metadata
::builder()
1828 .level(Level
::Debug
)
1831 assert_eq
!(metadata_test
.level(), Level
::Debug
);
1832 assert_eq
!(metadata_test
.target(), "myApp");
1836 fn test_record_builder() {
1837 use super::{MetadataBuilder, RecordBuilder}
;
1838 let target
= "myApp";
1839 let metadata
= MetadataBuilder
::new().target(target
).build();
1840 let fmt_args
= format_args
!("hello");
1841 let record_test
= RecordBuilder
::new()
1844 .module_path(Some("foo"))
1848 assert_eq
!(record_test
.metadata().target(), "myApp");
1849 assert_eq
!(record_test
.module_path(), Some("foo"));
1850 assert_eq
!(record_test
.file(), Some("bar"));
1851 assert_eq
!(record_test
.line(), Some(30));
1855 fn test_record_convenience_builder() {
1856 use super::{Metadata, Record}
;
1857 let target
= "myApp";
1858 let metadata
= Metadata
::builder().target(target
).build();
1859 let fmt_args
= format_args
!("hello");
1860 let record_test
= Record
::builder()
1863 .module_path(Some("foo"))
1867 assert_eq
!(record_test
.target(), "myApp");
1868 assert_eq
!(record_test
.module_path(), Some("foo"));
1869 assert_eq
!(record_test
.file(), Some("bar"));
1870 assert_eq
!(record_test
.line(), Some(30));
1874 fn test_record_complete_builder() {
1875 use super::{Level, Record}
;
1876 let target
= "myApp";
1877 let record_test
= Record
::builder()
1878 .module_path(Some("foo"))
1882 .level(Level
::Error
)
1884 assert_eq
!(record_test
.target(), "myApp");
1885 assert_eq
!(record_test
.level(), Level
::Error
);
1886 assert_eq
!(record_test
.module_path(), Some("foo"));
1887 assert_eq
!(record_test
.file(), Some("bar"));
1888 assert_eq
!(record_test
.line(), Some(30));
1892 #[cfg(feature = "kv_unstable")]
1893 fn test_record_key_values_builder() {
1895 use kv
::{self, Visitor}
;
1897 struct TestVisitor
{
1901 impl<'kvs
> Visitor
<'kvs
> for TestVisitor
{
1906 ) -> Result
<(), kv
::Error
> {
1907 self.seen_pairs
+= 1;
1912 let kvs
: &[(&str, i32)] = &[("a", 1), ("b", 2)];
1913 let record_test
= Record
::builder().key_values(&kvs
).build();
1915 let mut visitor
= TestVisitor { seen_pairs: 0 }
;
1917 record_test
.key_values().visit(&mut visitor
).unwrap();
1919 assert_eq
!(2, visitor
.seen_pairs
);
1923 #[cfg(feature = "kv_unstable")]
1924 fn test_record_key_values_get_coerce() {
1927 let kvs
: &[(&str, &str)] = &[("a", "1"), ("b", "2")];
1928 let record
= Record
::builder().key_values(&kvs
).build();
1935 .expect("missing key")
1937 .expect("invalid value")
1941 // Test that the `impl Log for Foo` blocks work
1942 // This test mostly operates on a type level, so failures will be compile errors
1944 fn test_foreign_impl() {
1946 #[cfg(feature = "std")]
1949 fn assert_is_log
<T
: Log
+ ?Sized
>() {}
1951 assert_is_log
::<&dyn Log
>();
1953 #[cfg(feature = "std")]
1954 assert_is_log
::<Box
<dyn Log
>>();
1956 #[cfg(feature = "std")]
1957 assert_is_log
::<Arc
<dyn Log
>>();
1959 // Assert these statements for all T: Log + ?Sized
1961 fn forall
<T
: Log
+ ?Sized
>() {
1962 #[cfg(feature = "std")]
1963 assert_is_log
::<Box
<T
>>();
1965 assert_is_log
::<&T
>();
1967 #[cfg(feature = "std")]
1968 assert_is_log
::<Arc
<T
>>();