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