log/
lib.rs

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