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