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