1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! A lightweight logging facade.
13 //! The `log` crate provides a single logging API that abstracts over the
14 //! actual logging implementation. Libraries can use the logging API provided
15 //! by this crate, and the consumer of those libraries can choose the logging
16 //! implementation that is most suitable for its use case.
18 //! If no logging implementation is selected, the facade falls back to a "noop"
19 //! implementation that ignores all log messages. The overhead in this case
20 //! is very small - just an integer load, comparison and jump.
22 //! A log request consists of a _target_, a _level_, and a _body_. A target is a
23 //! string which defaults to the module path of the location of the log request,
24 //! though that default may be overridden. Logger implementations typically use
25 //! the target to filter requests based on some user configuration.
29 //! The basic use of the log crate is through the five logging macros: [`error!`],
30 //! [`warn!`], [`info!`], [`debug!`] and [`trace!`]
31 //! where `error!` represents the highest-priority log messages
32 //! and `trace!` the lowest. The log messages are filtered by configuring
33 //! the log level to exclude messages with a lower priority.
34 //! Each of these macros accept format strings similarly to [`println!`].
37 //! [`error!`]: ./macro.error.html
38 //! [`warn!`]: ./macro.warn.html
39 //! [`info!`]: ./macro.info.html
40 //! [`debug!`]: ./macro.debug.html
41 //! [`trace!`]: ./macro.trace.html
42 //! [`println!`]: https://doc.rust-lang.org/stable/std/macro.println.html
46 //! Libraries should link only to the `log` crate, and use the provided
47 //! macros to log whatever information will be useful to downstream consumers.
52 //! # #[derive(Debug)] pub struct Yak(String);
53 //! # impl Yak { fn shave(&mut self, _: u32) {} }
54 //! # fn find_a_razor() -> Result<u32, u32> { Ok(1) }
55 //! use log::{info, warn};
57 //! pub fn shave_the_yak(yak: &mut Yak) {
58 //! info!(target: "yak_events", "Commencing yak shaving for {:?}", yak);
61 //! match find_a_razor() {
63 //! info!("Razor located: {}", razor);
68 //! warn!("Unable to locate a razor: {}, retrying", err);
78 //! Executables should choose a logging implementation and initialize it early in the
79 //! runtime of the program. Logging implementations will typically include a
80 //! function to do this. Any log messages generated before
81 //! the implementation is initialized will be ignored.
83 //! The executable itself may use the `log` crate to log as well.
87 //! The logging system may only be initialized once.
89 //! ## Structured logging
91 //! If you enable the `kv_unstable` feature you can associate structured values
92 //! with your log records. If we take the example from before, we can include
93 //! some additional context besides what's in the formatted message:
96 //! # #[macro_use] extern crate serde;
97 //! # #[derive(Debug, Serialize)] pub struct Yak(String);
98 //! # impl Yak { fn shave(&mut self, _: u32) {} }
99 //! # fn find_a_razor() -> Result<u32, std::io::Error> { Ok(1) }
100 //! # #[cfg(feature = "kv_unstable_serde")]
102 //! use log::{info, warn, as_serde, as_error};
104 //! pub fn shave_the_yak(yak: &mut Yak) {
105 //! info!(target: "yak_events", yak = as_serde!(yak); "Commencing yak shaving");
108 //! match find_a_razor() {
110 //! info!(razor = razor; "Razor located");
111 //! yak.shave(razor);
115 //! warn!(err = as_error!(err); "Unable to locate a razor, retrying");
121 //! # #[cfg(not(feature = "kv_unstable_serde"))]
125 //! # Available logging implementations
127 //! In order to produce log output executables have to use
128 //! a logger implementation compatible with the facade.
129 //! There are many available implementations to choose from,
130 //! here are some of the most popular ones:
132 //! * Simple minimal loggers:
134 //! * [simple_logger]
136 //! * [pretty_env_logger]
140 //! * [structured-logger]
141 //! * Complex configurable frameworks:
144 //! * Adaptors for other facilities:
147 //! * [systemd-journal-logger]
149 //! * [win_dbg_logger]
152 //! * For WebAssembly binaries:
154 //! * For dynamic libraries:
155 //! * You may need to construct an FFI-safe wrapper over `log` to initialize in your libraries
157 //! # Implementing a Logger
159 //! Loggers implement the [`Log`] trait. Here's a very basic example that simply
160 //! logs all messages at the [`Error`][level_link], [`Warn`][level_link] or
161 //! [`Info`][level_link] levels to stdout:
164 //! use log::{Record, Level, Metadata};
166 //! struct SimpleLogger;
168 //! impl log::Log for SimpleLogger {
169 //! fn enabled(&self, metadata: &Metadata) -> bool {
170 //! metadata.level() <= Level::Info
173 //! fn log(&self, record: &Record) {
174 //! if self.enabled(record.metadata()) {
175 //! println!("{} - {}", record.level(), record.args());
179 //! fn flush(&self) {}
185 //! Loggers are installed by calling the [`set_logger`] function. The maximum
186 //! log level also needs to be adjusted via the [`set_max_level`] function. The
187 //! logging facade uses this as an optimization to improve performance of log
188 //! messages at levels that are disabled. It's important to set it, as it
189 //! defaults to [`Off`][filter_link], so no log messages will ever be captured!
190 //! In the case of our example logger, we'll want to set the maximum log level
191 //! to [`Info`][filter_link], since we ignore any [`Debug`][level_link] or
192 //! [`Trace`][level_link] level log messages. A logging implementation should
193 //! provide a function that wraps a call to [`set_logger`] and
194 //! [`set_max_level`], handling initialization of the logger:
197 //! # use log::{Level, Metadata};
198 //! # struct SimpleLogger;
199 //! # impl log::Log for SimpleLogger {
200 //! # fn enabled(&self, _: &Metadata) -> bool { false }
201 //! # fn log(&self, _: &log::Record) {}
202 //! # fn flush(&self) {}
205 //! use log::{SetLoggerError, LevelFilter};
207 //! static LOGGER: SimpleLogger = SimpleLogger;
209 //! pub fn init() -> Result<(), SetLoggerError> {
210 //! log::set_logger(&LOGGER)
211 //! .map(|()| log::set_max_level(LevelFilter::Info))
215 //! Implementations that adjust their configurations at runtime should take care
216 //! to adjust the maximum log level as well.
220 //! `set_logger` requires you to provide a `&'static Log`, which can be hard to
221 //! obtain if your logger depends on some runtime configuration. The
222 //! `set_boxed_logger` function is available with the `std` Cargo feature. It is
223 //! identical to `set_logger` except that it takes a `Box<Log>` rather than a
227 //! # use log::{Level, LevelFilter, Log, SetLoggerError, Metadata};
228 //! # struct SimpleLogger;
229 //! # impl log::Log for SimpleLogger {
230 //! # fn enabled(&self, _: &Metadata) -> bool { false }
231 //! # fn log(&self, _: &log::Record) {}
232 //! # fn flush(&self) {}
235 //! # #[cfg(feature = "std")]
236 //! pub fn init() -> Result<(), SetLoggerError> {
237 //! log::set_boxed_logger(Box::new(SimpleLogger))
238 //! .map(|()| log::set_max_level(LevelFilter::Info))
242 //! # Compile time filters
244 //! Log levels can be statically disabled at compile time via Cargo features. Log invocations at
245 //! disabled levels will be skipped and will not even be present in the resulting binary.
246 //! This level is configured separately for release and debug builds. The features are:
248 //! * `max_level_off`
249 //! * `max_level_error`
250 //! * `max_level_warn`
251 //! * `max_level_info`
252 //! * `max_level_debug`
253 //! * `max_level_trace`
254 //! * `release_max_level_off`
255 //! * `release_max_level_error`
256 //! * `release_max_level_warn`
257 //! * `release_max_level_info`
258 //! * `release_max_level_debug`
259 //! * `release_max_level_trace`
261 //! These features control the value of the `STATIC_MAX_LEVEL` constant. The logging macros check
262 //! this value before logging a message. By default, no levels are disabled.
264 //! Libraries should avoid using the max level features because they're global and can't be changed
265 //! once they're set.
267 //! For example, a crate can disable trace level logs in debug builds and trace, debug, and info
268 //! level logs in release builds with the following configuration:
272 //! log = { version = "0.4", features = ["max_level_debug", "release_max_level_warn"] }
274 //! # Crate Feature Flags
276 //! The following crate feature flags are available in addition to the filters. They are
277 //! configured in your `Cargo.toml`.
279 //! * `std` allows use of `std` crate instead of the default `core`. Enables using `std::error` and
280 //! `set_boxed_logger` functionality.
281 //! * `serde` enables support for serialization and deserialization of `Level` and `LevelFilter`.
285 //! log = { version = "0.4", features = ["std", "serde"] }
288 //! # Version compatibility
290 //! The 0.3 and 0.4 versions of the `log` crate are almost entirely compatible. Log messages
291 //! made using `log` 0.3 will forward transparently to a logger implementation using `log` 0.4. Log
292 //! messages made using `log` 0.4 will forward to a logger implementation using `log` 0.3, but the
293 //! module path and file name information associated with the message will unfortunately be lost.
295 //! [`Log`]: trait.Log.html
296 //! [level_link]: enum.Level.html
297 //! [filter_link]: enum.LevelFilter.html
298 //! [`set_logger`]: fn.set_logger.html
299 //! [`set_max_level`]: fn.set_max_level.html
300 //! [`try_set_logger_raw`]: fn.try_set_logger_raw.html
301 //! [`shutdown_logger_raw`]: fn.shutdown_logger_raw.html
302 //! [env_logger]: https://docs.rs/env_logger/*/env_logger/
303 //! [simple_logger]: https://github.com/borntyping/rust-simple_logger
304 //! [simplelog]: https://github.com/drakulix/simplelog.rs
305 //! [pretty_env_logger]: https://docs.rs/pretty_env_logger/*/pretty_env_logger/
306 //! [stderrlog]: https://docs.rs/stderrlog/*/stderrlog/
307 //! [flexi_logger]: https://docs.rs/flexi_logger/*/flexi_logger/
308 //! [call_logger]: https://docs.rs/call_logger/*/call_logger/
309 //! [syslog]: https://docs.rs/syslog/*/syslog/
310 //! [slog-stdlog]: https://docs.rs/slog-stdlog/*/slog_stdlog/
311 //! [log4rs]: https://docs.rs/log4rs/*/log4rs/
312 //! [fern]: https://docs.rs/fern/*/fern/
313 //! [systemd-journal-logger]: https://docs.rs/systemd-journal-logger/*/systemd_journal_logger/
314 //! [android_log]: https://docs.rs/android_log/*/android_log/
315 //! [win_dbg_logger]: https://docs.rs/win_dbg_logger/*/win_dbg_logger/
316 //! [db_logger]: https://docs.rs/db_logger/*/db_logger/
317 //! [log-to-defmt]: https://docs.rs/log-to-defmt/*/log_to_defmt/
318 //! [console_log]: https://docs.rs/console_log/*/console_log/
319 //! [structured-logger]: https://docs.rs/structured-logger/latest/structured_logger/
322 html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
323 html_favicon_url = "https://www.rust-lang.org/favicon.ico",
324 html_root_url = "https://docs.rs/log/0.4.20"
326 #![warn(missing_docs)]
327 #![deny(missing_debug_implementations, unconditional_recursion)]
328 #![cfg_attr(all(not(feature = "std"), not(test)), no_std)]
329 // When compiled for the rustc compiler itself we want to make sure that this is
331 #![cfg_attr(rustbuild, feature(staged_api, rustc_private))]
332 #![cfg_attr(rustbuild, unstable(feature = "rustc_private", issue = "27812"))]
334 #[cfg(all(not(feature = "std"), not(test)))]
335 extern crate core as std;
338 #[cfg(feature = "std")]
342 use std::str::FromStr;
348 #[cfg(feature = "kv_unstable")]
351 #[cfg(target_has_atomic = "ptr")]
352 use std::sync::atomic::{AtomicUsize, Ordering};
354 #[cfg(not(target_has_atomic = "ptr"))]
356 #[cfg(not(target_has_atomic = "ptr"))]
357 use std::sync::atomic::Ordering;
359 #[cfg(not(target_has_atomic = "ptr"))]
364 #[cfg(not(target_has_atomic = "ptr"))]
366 const fn new(v: usize) -> AtomicUsize {
367 AtomicUsize { v: Cell::new(v) }
370 fn load(&self, _order: Ordering) -> usize {
374 fn store(&self, val: usize, _order: Ordering) {
378 #[cfg(target_has_atomic = "ptr")]
385 ) -> Result<usize, usize> {
386 let prev = self.v.get();
394 // Any platform without atomics is unlikely to have multiple cores, so
395 // writing via Cell will not be a race condition.
396 #[cfg(not(target_has_atomic = "ptr"))]
397 unsafe impl Sync for AtomicUsize {}
399 // The LOGGER static holds a pointer to the global logger. It is protected by
400 // the STATE static which determines whether LOGGER has been initialized yet.
401 static mut LOGGER: &dyn Log = &NopLogger;
403 static STATE: AtomicUsize = AtomicUsize::new(0);
405 // There are three different states that we care about: the logger's
406 // uninitialized, the logger's initializing (set_logger's been called but
407 // LOGGER hasn't actually been set yet), or the logger's active.
408 const UNINITIALIZED: usize = 0;
409 const INITIALIZING: usize = 1;
410 const INITIALIZED: usize = 2;
412 static MAX_LOG_LEVEL_FILTER: AtomicUsize = AtomicUsize::new(0);
414 static LOG_LEVEL_NAMES: [&str; 6] = ["OFF", "ERROR", "WARN", "INFO", "DEBUG", "TRACE"];
416 static SET_LOGGER_ERROR: &str = "attempted to set a logger after the logging system \
417 was already initialized";
418 static LEVEL_PARSE_ERROR: &str =
419 "attempted to convert a string that doesn't match an existing log level";
421 /// An enum representing the available verbosity levels of the logger.
423 /// Typical usage includes: checking if a certain `Level` is enabled with
424 /// [`log_enabled!`](macro.log_enabled.html), specifying the `Level` of
425 /// [`log!`](macro.log.html), and comparing a `Level` directly to a
426 /// [`LevelFilter`](enum.LevelFilter.html).
428 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
430 /// The "error" level.
432 /// Designates very serious errors.
433 // This way these line up with the discriminants for LevelFilter below
434 // This works because Rust treats field-less enums the same way as C does:
435 // https://doc.rust-lang.org/reference/items/enumerations.html#custom-discriminant-values-for-field-less-enumerations
437 /// The "warn" level.
439 /// Designates hazardous situations.
441 /// The "info" level.
443 /// Designates useful information.
445 /// The "debug" level.
447 /// Designates lower priority information.
449 /// The "trace" level.
451 /// Designates very low priority, often extremely verbose, information.
455 impl PartialEq<LevelFilter> for Level {
457 fn eq(&self, other: &LevelFilter) -> bool {
458 *self as usize == *other as usize
462 impl PartialOrd<LevelFilter> for Level {
464 fn partial_cmp(&self, other: &LevelFilter) -> Option<cmp::Ordering> {
465 Some((*self as usize).cmp(&(*other as usize)))
469 fn ok_or<T, E>(t: Option<T>, e: E) -> Result<T, E> {
476 impl FromStr for Level {
477 type Err = ParseLevelError;
478 fn from_str(level: &str) -> Result<Level, Self::Err> {
482 .position(|&name| name.eq_ignore_ascii_case(level))
484 .filter(|&idx| idx != 0)
485 .map(|idx| Level::from_usize(idx).unwrap())
492 impl fmt::Display for Level {
493 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
494 fmt.pad(self.as_str())
499 fn from_usize(u: usize) -> Option<Level> {
501 1 => Some(Level::Error),
502 2 => Some(Level::Warn),
503 3 => Some(Level::Info),
504 4 => Some(Level::Debug),
505 5 => Some(Level::Trace),
510 /// Returns the most verbose logging level.
512 pub fn max() -> Level {
516 /// Converts the `Level` to the equivalent `LevelFilter`.
518 pub fn to_level_filter(&self) -> LevelFilter {
519 LevelFilter::from_usize(*self as usize).unwrap()
522 /// Returns the string representation of the `Level`.
524 /// This returns the same string as the `fmt::Display` implementation.
525 pub fn as_str(&self) -> &'static str {
526 LOG_LEVEL_NAMES[*self as usize]
529 /// Iterate through all supported logging levels.
531 /// The order of iteration is from more severe to less severe log messages.
538 /// let mut levels = Level::iter();
540 /// assert_eq!(Some(Level::Error), levels.next());
541 /// assert_eq!(Some(Level::Trace), levels.last());
543 pub fn iter() -> impl Iterator<Item = Self> {
544 (1..6).map(|i| Self::from_usize(i).unwrap())
548 /// An enum representing the available verbosity level filters of the logger.
550 /// A `LevelFilter` may be compared directly to a [`Level`]. Use this type
551 /// to get and set the maximum log level with [`max_level()`] and [`set_max_level`].
553 /// [`Level`]: enum.Level.html
554 /// [`max_level()`]: fn.max_level.html
555 /// [`set_max_level`]: fn.set_max_level.html
557 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
558 pub enum LevelFilter {
559 /// A level lower than all log levels.
561 /// Corresponds to the `Error` log level.
563 /// Corresponds to the `Warn` log level.
565 /// Corresponds to the `Info` log level.
567 /// Corresponds to the `Debug` log level.
569 /// Corresponds to the `Trace` log level.
573 impl PartialEq<Level> for LevelFilter {
575 fn eq(&self, other: &Level) -> bool {
580 impl PartialOrd<Level> for LevelFilter {
582 fn partial_cmp(&self, other: &Level) -> Option<cmp::Ordering> {
583 Some((*self as usize).cmp(&(*other as usize)))
587 impl FromStr for LevelFilter {
588 type Err = ParseLevelError;
589 fn from_str(level: &str) -> Result<LevelFilter, Self::Err> {
593 .position(|&name| name.eq_ignore_ascii_case(level))
594 .map(|p| LevelFilter::from_usize(p).unwrap()),
600 impl fmt::Display for LevelFilter {
601 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
602 fmt.pad(self.as_str())
607 fn from_usize(u: usize) -> Option<LevelFilter> {
609 0 => Some(LevelFilter::Off),
610 1 => Some(LevelFilter::Error),
611 2 => Some(LevelFilter::Warn),
612 3 => Some(LevelFilter::Info),
613 4 => Some(LevelFilter::Debug),
614 5 => Some(LevelFilter::Trace),
619 /// Returns the most verbose logging level filter.
621 pub fn max() -> LevelFilter {
625 /// Converts `self` to the equivalent `Level`.
627 /// Returns `None` if `self` is `LevelFilter::Off`.
629 pub fn to_level(&self) -> Option<Level> {
630 Level::from_usize(*self as usize)
633 /// Returns the string representation of the `LevelFilter`.
635 /// This returns the same string as the `fmt::Display` implementation.
636 pub fn as_str(&self) -> &'static str {
637 LOG_LEVEL_NAMES[*self as usize]
640 /// Iterate through all supported filtering levels.
642 /// The order of iteration is from less to more verbose filtering.
647 /// use log::LevelFilter;
649 /// let mut levels = LevelFilter::iter();
651 /// assert_eq!(Some(LevelFilter::Off), levels.next());
652 /// assert_eq!(Some(LevelFilter::Trace), levels.last());
654 pub fn iter() -> impl Iterator<Item = Self> {
655 (0..6).map(|i| Self::from_usize(i).unwrap())
659 #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
660 enum MaybeStaticStr<'a> {
661 Static(&'static str),
665 impl<'a> MaybeStaticStr<'a> {
667 fn get(&self) -> &'a str {
669 MaybeStaticStr::Static(s) => s,
670 MaybeStaticStr::Borrowed(s) => s,
675 /// The "payload" of a log message.
679 /// `Record` structures are passed as parameters to the [`log`][method.log]
680 /// method of the [`Log`] trait. Logger implementors manipulate these
681 /// structures in order to display log messages. `Record`s are automatically
682 /// created by the [`log!`] macro and so are not seen by log users.
684 /// Note that the [`level()`] and [`target()`] accessors are equivalent to
685 /// `self.metadata().level()` and `self.metadata().target()` respectively.
686 /// These methods are provided as a convenience for users of this structure.
690 /// The following example shows a simple logger that displays the level,
691 /// module path, and message of any `Record` that is passed to it.
694 /// struct SimpleLogger;
696 /// impl log::Log for SimpleLogger {
697 /// fn enabled(&self, _metadata: &log::Metadata) -> bool {
701 /// fn log(&self, record: &log::Record) {
702 /// if !self.enabled(record.metadata()) {
706 /// println!("{}:{} -- {}",
711 /// fn flush(&self) {}
715 /// [method.log]: trait.Log.html#tymethod.log
716 /// [`Log`]: trait.Log.html
717 /// [`log!`]: macro.log.html
718 /// [`level()`]: struct.Record.html#method.level
719 /// [`target()`]: struct.Record.html#method.target
720 #[derive(Clone, Debug)]
721 pub struct Record<'a> {
722 metadata: Metadata<'a>,
723 args: fmt::Arguments<'a>,
724 module_path: Option<MaybeStaticStr<'a>>,
725 file: Option<MaybeStaticStr<'a>>,
727 #[cfg(feature = "kv_unstable")]
728 key_values: KeyValues<'a>,
731 // This wrapper type is only needed so we can
732 // `#[derive(Debug)]` on `Record`. It also
733 // provides a useful `Debug` implementation for
734 // the underlying `Source`.
735 #[cfg(feature = "kv_unstable")]
737 struct KeyValues<'a>(&'a dyn kv::Source);
739 #[cfg(feature = "kv_unstable")]
740 impl<'a> fmt::Debug for KeyValues<'a> {
741 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
742 let mut visitor = f.debug_map();
743 self.0.visit(&mut visitor).map_err(|_| fmt::Error)?;
748 impl<'a> Record<'a> {
749 /// Returns a new builder.
751 pub fn builder() -> RecordBuilder<'a> {
755 /// The message body.
757 pub fn args(&self) -> &fmt::Arguments<'a> {
761 /// Metadata about the log directive.
763 pub fn metadata(&self) -> &Metadata<'a> {
767 /// The verbosity level of the message.
769 pub fn level(&self) -> Level {
770 self.metadata.level()
773 /// The name of the target of the directive.
775 pub fn target(&self) -> &'a str {
776 self.metadata.target()
779 /// The module path of the message.
781 pub fn module_path(&self) -> Option<&'a str> {
782 self.module_path.map(|s| s.get())
785 /// The module path of the message, if it is a `'static` string.
787 pub fn module_path_static(&self) -> Option<&'static str> {
788 match self.module_path {
789 Some(MaybeStaticStr::Static(s)) => Some(s),
794 /// The source file containing the message.
796 pub fn file(&self) -> Option<&'a str> {
797 self.file.map(|s| s.get())
800 /// The module path of the message, if it is a `'static` string.
802 pub fn file_static(&self) -> Option<&'static str> {
804 Some(MaybeStaticStr::Static(s)) => Some(s),
809 /// The line containing the message.
811 pub fn line(&self) -> Option<u32> {
815 /// The structured key-value pairs associated with the message.
816 #[cfg(feature = "kv_unstable")]
818 pub fn key_values(&self) -> &dyn kv::Source {
822 /// Create a new [`RecordBuilder`](struct.RecordBuilder.html) based on this record.
823 #[cfg(feature = "kv_unstable")]
825 pub fn to_builder(&self) -> RecordBuilder {
829 level: self.metadata.level,
830 target: self.metadata.target,
833 module_path: self.module_path,
836 key_values: self.key_values.clone(),
842 /// Builder for [`Record`](struct.Record.html).
844 /// Typically should only be used by log library creators or for testing and "shim loggers".
845 /// The `RecordBuilder` can set the different parameters of `Record` object, and returns
846 /// the created object when `build` is called.
851 /// use log::{Level, Record};
853 /// let record = Record::builder()
854 /// .args(format_args!("Error!"))
855 /// .level(Level::Error)
857 /// .file(Some("server.rs"))
859 /// .module_path(Some("server"))
863 /// Alternatively, use [`MetadataBuilder`](struct.MetadataBuilder.html):
866 /// use log::{Record, Level, MetadataBuilder};
868 /// let error_metadata = MetadataBuilder::new()
870 /// .level(Level::Error)
873 /// let record = Record::builder()
874 /// .metadata(error_metadata)
875 /// .args(format_args!("Error!"))
877 /// .file(Some("app.rs"))
878 /// .module_path(Some("server"))
882 pub struct RecordBuilder<'a> {
886 impl<'a> RecordBuilder<'a> {
887 /// Construct new `RecordBuilder`.
889 /// The default options are:
891 /// - `args`: [`format_args!("")`]
892 /// - `metadata`: [`Metadata::builder().build()`]
893 /// - `module_path`: `None`
897 /// [`format_args!("")`]: https://doc.rust-lang.org/std/macro.format_args.html
898 /// [`Metadata::builder().build()`]: struct.MetadataBuilder.html#method.build
900 pub fn new() -> RecordBuilder<'a> {
903 args: format_args!(""),
904 metadata: Metadata::builder().build(),
908 #[cfg(feature = "kv_unstable")]
909 key_values: KeyValues(&Option::None::<(kv::Key, kv::Value)>),
914 /// Set [`args`](struct.Record.html#method.args).
916 pub fn args(&mut self, args: fmt::Arguments<'a>) -> &mut RecordBuilder<'a> {
917 self.record.args = args;
921 /// Set [`metadata`](struct.Record.html#method.metadata). Construct a `Metadata` object with [`MetadataBuilder`](struct.MetadataBuilder.html).
923 pub fn metadata(&mut self, metadata: Metadata<'a>) -> &mut RecordBuilder<'a> {
924 self.record.metadata = metadata;
928 /// Set [`Metadata::level`](struct.Metadata.html#method.level).
930 pub fn level(&mut self, level: Level) -> &mut RecordBuilder<'a> {
931 self.record.metadata.level = level;
935 /// Set [`Metadata::target`](struct.Metadata.html#method.target)
937 pub fn target(&mut self, target: &'a str) -> &mut RecordBuilder<'a> {
938 self.record.metadata.target = target;
942 /// Set [`module_path`](struct.Record.html#method.module_path)
944 pub fn module_path(&mut self, path: Option<&'a str>) -> &mut RecordBuilder<'a> {
945 self.record.module_path = path.map(MaybeStaticStr::Borrowed);
949 /// Set [`module_path`](struct.Record.html#method.module_path) to a `'static` string
951 pub fn module_path_static(&mut self, path: Option<&'static str>) -> &mut RecordBuilder<'a> {
952 self.record.module_path = path.map(MaybeStaticStr::Static);
956 /// Set [`file`](struct.Record.html#method.file)
958 pub fn file(&mut self, file: Option<&'a str>) -> &mut RecordBuilder<'a> {
959 self.record.file = file.map(MaybeStaticStr::Borrowed);
963 /// Set [`file`](struct.Record.html#method.file) to a `'static` string.
965 pub fn file_static(&mut self, file: Option<&'static str>) -> &mut RecordBuilder<'a> {
966 self.record.file = file.map(MaybeStaticStr::Static);
970 /// Set [`line`](struct.Record.html#method.line)
972 pub fn line(&mut self, line: Option<u32>) -> &mut RecordBuilder<'a> {
973 self.record.line = line;
977 /// Set [`key_values`](struct.Record.html#method.key_values)
978 #[cfg(feature = "kv_unstable")]
980 pub fn key_values(&mut self, kvs: &'a dyn kv::Source) -> &mut RecordBuilder<'a> {
981 self.record.key_values = KeyValues(kvs);
985 /// Invoke the builder and return a `Record`
987 pub fn build(&self) -> Record<'a> {
992 impl<'a> Default for RecordBuilder<'a> {
993 fn default() -> Self {
998 /// Metadata about a log message.
1002 /// `Metadata` structs are created when users of the library use
1005 /// They are consumed by implementations of the `Log` trait in the
1006 /// `enabled` method.
1008 /// `Record`s use `Metadata` to determine the log message's severity
1011 /// Users should use the `log_enabled!` macro in their code to avoid
1012 /// constructing expensive log messages.
1017 /// use log::{Record, Level, Metadata};
1019 /// struct MyLogger;
1021 /// impl log::Log for MyLogger {
1022 /// fn enabled(&self, metadata: &Metadata) -> bool {
1023 /// metadata.level() <= Level::Info
1026 /// fn log(&self, record: &Record) {
1027 /// if self.enabled(record.metadata()) {
1028 /// println!("{} - {}", record.level(), record.args());
1031 /// fn flush(&self) {}
1036 #[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
1037 pub struct Metadata<'a> {
1042 impl<'a> Metadata<'a> {
1043 /// Returns a new builder.
1045 pub fn builder() -> MetadataBuilder<'a> {
1046 MetadataBuilder::new()
1049 /// The verbosity level of the message.
1051 pub fn level(&self) -> Level {
1055 /// The name of the target of the directive.
1057 pub fn target(&self) -> &'a str {
1062 /// Builder for [`Metadata`](struct.Metadata.html).
1064 /// Typically should only be used by log library creators or for testing and "shim loggers".
1065 /// The `MetadataBuilder` can set the different parameters of a `Metadata` object, and returns
1066 /// the created object when `build` is called.
1071 /// let target = "myApp";
1072 /// use log::{Level, MetadataBuilder};
1073 /// let metadata = MetadataBuilder::new()
1074 /// .level(Level::Debug)
1078 #[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
1079 pub struct MetadataBuilder<'a> {
1080 metadata: Metadata<'a>,
1083 impl<'a> MetadataBuilder<'a> {
1084 /// Construct a new `MetadataBuilder`.
1086 /// The default options are:
1088 /// - `level`: `Level::Info`
1089 /// - `target`: `""`
1091 pub fn new() -> MetadataBuilder<'a> {
1093 metadata: Metadata {
1100 /// Setter for [`level`](struct.Metadata.html#method.level).
1102 pub fn level(&mut self, arg: Level) -> &mut MetadataBuilder<'a> {
1103 self.metadata.level = arg;
1107 /// Setter for [`target`](struct.Metadata.html#method.target).
1109 pub fn target(&mut self, target: &'a str) -> &mut MetadataBuilder<'a> {
1110 self.metadata.target = target;
1114 /// Returns a `Metadata` object.
1116 pub fn build(&self) -> Metadata<'a> {
1117 self.metadata.clone()
1121 impl<'a> Default for MetadataBuilder<'a> {
1122 fn default() -> Self {
1127 /// A trait encapsulating the operations required of a logger.
1128 pub trait Log: Sync + Send {
1129 /// Determines if a log message with the specified metadata would be
1132 /// This is used by the `log_enabled!` macro to allow callers to avoid
1133 /// expensive computation of log message arguments if the message would be
1134 /// discarded anyway.
1136 /// # For implementors
1138 /// This method isn't called automatically by the `log!` macros.
1139 /// It's up to an implementation of the `Log` trait to call `enabled` in its own
1140 /// `log` method implementation to guarantee that filtering is applied.
1141 fn enabled(&self, metadata: &Metadata) -> bool;
1143 /// Logs the `Record`.
1145 /// # For implementors
1147 /// Note that `enabled` is *not* necessarily called before this method.
1148 /// Implementations of `log` should perform all necessary filtering
1150 fn log(&self, record: &Record);
1152 /// Flushes any buffered records.
1156 // Just used as a dummy initial value for LOGGER
1159 impl Log for NopLogger {
1160 fn enabled(&self, _: &Metadata) -> bool {
1164 fn log(&self, _: &Record) {}
1168 impl<T> Log for &'_ T
1172 fn enabled(&self, metadata: &Metadata) -> bool {
1173 (**self).enabled(metadata)
1176 fn log(&self, record: &Record) {
1177 (**self).log(record);
1184 #[cfg(feature = "std")]
1185 impl<T> Log for std::boxed::Box<T>
1189 fn enabled(&self, metadata: &Metadata) -> bool {
1190 self.as_ref().enabled(metadata)
1193 fn log(&self, record: &Record) {
1194 self.as_ref().log(record)
1197 self.as_ref().flush()
1201 #[cfg(feature = "std")]
1202 impl<T> Log for std::sync::Arc<T>
1206 fn enabled(&self, metadata: &Metadata) -> bool {
1207 self.as_ref().enabled(metadata)
1210 fn log(&self, record: &Record) {
1211 self.as_ref().log(record)
1214 self.as_ref().flush()
1218 /// Sets the global maximum log level.
1220 /// Generally, this should only be called by the active logging implementation.
1222 /// Note that `Trace` is the maximum level, because it provides the maximum amount of detail in the emitted logs.
1224 #[cfg(target_has_atomic = "ptr")]
1225 pub fn set_max_level(level: LevelFilter) {
1226 MAX_LOG_LEVEL_FILTER.store(level as usize, Ordering::Relaxed);
1229 /// A thread-unsafe version of [`set_max_level`].
1231 /// This function is available on all platforms, even those that do not have
1232 /// support for atomics that is needed by [`set_max_level`].
1234 /// In almost all cases, [`set_max_level`] should be preferred.
1238 /// This function is only safe to call when no other level setting function is
1239 /// called while this function still executes.
1241 /// This can be upheld by (for example) making sure that **there are no other
1242 /// threads**, and (on embedded) that **interrupts are disabled**.
1244 /// Is is safe to use all other logging functions while this function runs
1245 /// (including all logging macros).
1247 /// [`set_max_level`]: fn.set_max_level.html
1249 pub unsafe fn set_max_level_racy(level: LevelFilter) {
1250 // `MAX_LOG_LEVEL_FILTER` uses a `Cell` as the underlying primitive when a
1251 // platform doesn't support `target_has_atomic = "ptr"`, so even though this looks the same
1252 // as `set_max_level` it may have different safety properties.
1253 MAX_LOG_LEVEL_FILTER.store(level as usize, Ordering::Relaxed);
1256 /// Returns the current maximum log level.
1258 /// The [`log!`], [`error!`], [`warn!`], [`info!`], [`debug!`], and [`trace!`] macros check
1259 /// this value and discard any message logged at a higher level. The maximum
1260 /// log level is set by the [`set_max_level`] function.
1262 /// [`log!`]: macro.log.html
1263 /// [`error!`]: macro.error.html
1264 /// [`warn!`]: macro.warn.html
1265 /// [`info!`]: macro.info.html
1266 /// [`debug!`]: macro.debug.html
1267 /// [`trace!`]: macro.trace.html
1268 /// [`set_max_level`]: fn.set_max_level.html
1270 pub fn max_level() -> LevelFilter {
1271 // Since `LevelFilter` is `repr(usize)`,
1272 // this transmute is sound if and only if `MAX_LOG_LEVEL_FILTER`
1273 // is set to a usize that is a valid discriminant for `LevelFilter`.
1274 // Since `MAX_LOG_LEVEL_FILTER` is private, the only time it's set
1275 // is by `set_max_level` above, i.e. by casting a `LevelFilter` to `usize`.
1276 // So any usize stored in `MAX_LOG_LEVEL_FILTER` is a valid discriminant.
1277 unsafe { mem::transmute(MAX_LOG_LEVEL_FILTER.load(Ordering::Relaxed)) }
1280 /// Sets the global logger to a `Box<Log>`.
1282 /// This is a simple convenience wrapper over `set_logger`, which takes a
1283 /// `Box<Log>` rather than a `&'static Log`. See the documentation for
1284 /// [`set_logger`] for more details.
1286 /// Requires the `std` feature.
1290 /// An error is returned if a logger has already been set.
1292 /// [`set_logger`]: fn.set_logger.html
1293 #[cfg(all(feature = "std", target_has_atomic = "ptr"))]
1294 pub fn set_boxed_logger(logger: Box<dyn Log>) -> Result<(), SetLoggerError> {
1295 set_logger_inner(|| Box::leak(logger))
1298 /// Sets the global logger to a `&'static Log`.
1300 /// This function may only be called once in the lifetime of a program. Any log
1301 /// events that occur before the call to `set_logger` completes will be ignored.
1303 /// This function does not typically need to be called manually. Logger
1304 /// implementations should provide an initialization method that installs the
1305 /// logger internally.
1309 /// This method is available even when the `std` feature is disabled. However,
1310 /// it is currently unavailable on `thumbv6` targets, which lack support for
1311 /// some atomic operations which are used by this function. Even on those
1312 /// targets, [`set_logger_racy`] will be available.
1316 /// An error is returned if a logger has already been set.
1321 /// use log::{error, info, warn, Record, Level, Metadata, LevelFilter};
1323 /// static MY_LOGGER: MyLogger = MyLogger;
1325 /// struct MyLogger;
1327 /// impl log::Log for MyLogger {
1328 /// fn enabled(&self, metadata: &Metadata) -> bool {
1329 /// metadata.level() <= Level::Info
1332 /// fn log(&self, record: &Record) {
1333 /// if self.enabled(record.metadata()) {
1334 /// println!("{} - {}", record.level(), record.args());
1337 /// fn flush(&self) {}
1341 /// log::set_logger(&MY_LOGGER).unwrap();
1342 /// log::set_max_level(LevelFilter::Info);
1344 /// info!("hello log");
1345 /// warn!("warning");
1350 /// [`set_logger_racy`]: fn.set_logger_racy.html
1351 #[cfg(target_has_atomic = "ptr")]
1352 pub fn set_logger(logger: &'static dyn Log) -> Result<(), SetLoggerError> {
1353 set_logger_inner(|| logger)
1356 #[cfg(target_has_atomic = "ptr")]
1357 fn set_logger_inner<F>(make_logger: F) -> Result<(), SetLoggerError>
1359 F: FnOnce() -> &'static dyn Log,
1361 let old_state = match STATE.compare_exchange(
1367 Ok(s) | Err(s) => s,
1372 LOGGER = make_logger();
1374 STATE.store(INITIALIZED, Ordering::SeqCst);
1378 while STATE.load(Ordering::SeqCst) == INITIALIZING {
1379 // TODO: replace with `hint::spin_loop` once MSRV is 1.49.0.
1380 #[allow(deprecated)]
1381 std::sync::atomic::spin_loop_hint();
1383 Err(SetLoggerError(()))
1385 _ => Err(SetLoggerError(())),
1389 /// A thread-unsafe version of [`set_logger`].
1391 /// This function is available on all platforms, even those that do not have
1392 /// support for atomics that is needed by [`set_logger`].
1394 /// In almost all cases, [`set_logger`] should be preferred.
1398 /// This function is only safe to call when no other logger initialization
1399 /// function is called while this function still executes.
1401 /// This can be upheld by (for example) making sure that **there are no other
1402 /// threads**, and (on embedded) that **interrupts are disabled**.
1404 /// It is safe to use other logging functions while this function runs
1405 /// (including all logging macros).
1407 /// [`set_logger`]: fn.set_logger.html
1408 pub unsafe fn set_logger_racy(logger: &'static dyn Log) -> Result<(), SetLoggerError> {
1409 match STATE.load(Ordering::SeqCst) {
1412 STATE.store(INITIALIZED, Ordering::SeqCst);
1416 // This is just plain UB, since we were racing another initialization function
1417 unreachable!("set_logger_racy must not be used with other initialization functions")
1419 _ => Err(SetLoggerError(())),
1423 /// The type returned by [`set_logger`] if [`set_logger`] has already been called.
1425 /// [`set_logger`]: fn.set_logger.html
1426 #[allow(missing_copy_implementations)]
1428 pub struct SetLoggerError(());
1430 impl fmt::Display for SetLoggerError {
1431 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1432 fmt.write_str(SET_LOGGER_ERROR)
1436 // The Error trait is not available in libcore
1437 #[cfg(feature = "std")]
1438 impl error::Error for SetLoggerError {}
1440 /// The type returned by [`from_str`] when the string doesn't match any of the log levels.
1442 /// [`from_str`]: https://doc.rust-lang.org/std/str/trait.FromStr.html#tymethod.from_str
1443 #[allow(missing_copy_implementations)]
1444 #[derive(Debug, PartialEq, Eq)]
1445 pub struct ParseLevelError(());
1447 impl fmt::Display for ParseLevelError {
1448 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1449 fmt.write_str(LEVEL_PARSE_ERROR)
1453 // The Error trait is not available in libcore
1454 #[cfg(feature = "std")]
1455 impl error::Error for ParseLevelError {}
1457 /// Returns a reference to the logger.
1459 /// If a logger has not been set, a no-op implementation is returned.
1460 pub fn logger() -> &'static dyn Log {
1461 if STATE.load(Ordering::SeqCst) != INITIALIZED {
1462 static NOP: NopLogger = NopLogger;
1469 // WARNING: this is not part of the crate's public API and is subject to change at any time
1471 pub mod __private_api;
1473 /// The statically resolved maximum log level.
1475 /// See the crate level documentation for information on how to configure this.
1477 /// This value is checked by the log macros, but not by the `Log`ger returned by
1478 /// the [`logger`] function. Code that manually calls functions on that value
1479 /// should compare the level against this value.
1481 /// [`logger`]: fn.logger.html
1482 pub const STATIC_MAX_LEVEL: LevelFilter = MAX_LEVEL_INNER;
1484 const MAX_LEVEL_INNER: LevelFilter = get_max_level_inner();
1486 const fn get_max_level_inner() -> LevelFilter {
1487 #[allow(unreachable_code)]
1489 #[cfg(all(not(debug_assertions), feature = "release_max_level_off"))]
1491 return LevelFilter::Off;
1493 #[cfg(all(not(debug_assertions), feature = "release_max_level_error"))]
1495 return LevelFilter::Error;
1497 #[cfg(all(not(debug_assertions), feature = "release_max_level_warn"))]
1499 return LevelFilter::Warn;
1501 #[cfg(all(not(debug_assertions), feature = "release_max_level_info"))]
1503 return LevelFilter::Info;
1505 #[cfg(all(not(debug_assertions), feature = "release_max_level_debug"))]
1507 return LevelFilter::Debug;
1509 #[cfg(all(not(debug_assertions), feature = "release_max_level_trace"))]
1511 return LevelFilter::Trace;
1513 #[cfg(feature = "max_level_off")]
1515 return LevelFilter::Off;
1517 #[cfg(feature = "max_level_error")]
1519 return LevelFilter::Error;
1521 #[cfg(feature = "max_level_warn")]
1523 return LevelFilter::Warn;
1525 #[cfg(feature = "max_level_info")]
1527 return LevelFilter::Info;
1529 #[cfg(feature = "max_level_debug")]
1531 return LevelFilter::Debug;
1541 use super::{Level, LevelFilter, ParseLevelError};
1542 use tests::std::string::ToString;
1545 fn test_levelfilter_from_str() {
1547 ("off", Ok(LevelFilter::Off)),
1548 ("error", Ok(LevelFilter::Error)),
1549 ("warn", Ok(LevelFilter::Warn)),
1550 ("info", Ok(LevelFilter::Info)),
1551 ("debug", Ok(LevelFilter::Debug)),
1552 ("trace", Ok(LevelFilter::Trace)),
1553 ("OFF", Ok(LevelFilter::Off)),
1554 ("ERROR", Ok(LevelFilter::Error)),
1555 ("WARN", Ok(LevelFilter::Warn)),
1556 ("INFO", Ok(LevelFilter::Info)),
1557 ("DEBUG", Ok(LevelFilter::Debug)),
1558 ("TRACE", Ok(LevelFilter::Trace)),
1559 ("asdf", Err(ParseLevelError(()))),
1561 for &(s, ref expected) in &tests {
1562 assert_eq!(expected, &s.parse());
1567 fn test_level_from_str() {
1569 ("OFF", Err(ParseLevelError(()))),
1570 ("error", Ok(Level::Error)),
1571 ("warn", Ok(Level::Warn)),
1572 ("info", Ok(Level::Info)),
1573 ("debug", Ok(Level::Debug)),
1574 ("trace", Ok(Level::Trace)),
1575 ("ERROR", Ok(Level::Error)),
1576 ("WARN", Ok(Level::Warn)),
1577 ("INFO", Ok(Level::Info)),
1578 ("DEBUG", Ok(Level::Debug)),
1579 ("TRACE", Ok(Level::Trace)),
1580 ("asdf", Err(ParseLevelError(()))),
1582 for &(s, ref expected) in &tests {
1583 assert_eq!(expected, &s.parse());
1588 fn test_level_as_str() {
1590 (Level::Error, "ERROR"),
1591 (Level::Warn, "WARN"),
1592 (Level::Info, "INFO"),
1593 (Level::Debug, "DEBUG"),
1594 (Level::Trace, "TRACE"),
1596 for (input, expected) in tests {
1597 assert_eq!(*expected, input.as_str());
1602 fn test_level_show() {
1603 assert_eq!("INFO", Level::Info.to_string());
1604 assert_eq!("ERROR", Level::Error.to_string());
1608 fn test_levelfilter_show() {
1609 assert_eq!("OFF", LevelFilter::Off.to_string());
1610 assert_eq!("ERROR", LevelFilter::Error.to_string());
1614 fn test_cross_cmp() {
1615 assert!(Level::Debug > LevelFilter::Error);
1616 assert!(LevelFilter::Warn < Level::Trace);
1617 assert!(LevelFilter::Off < Level::Error);
1621 fn test_cross_eq() {
1622 assert!(Level::Error == LevelFilter::Error);
1623 assert!(LevelFilter::Off != Level::Error);
1624 assert!(Level::Trace == LevelFilter::Trace);
1628 fn test_to_level() {
1629 assert_eq!(Some(Level::Error), LevelFilter::Error.to_level());
1630 assert_eq!(None, LevelFilter::Off.to_level());
1631 assert_eq!(Some(Level::Debug), LevelFilter::Debug.to_level());
1635 fn test_to_level_filter() {
1636 assert_eq!(LevelFilter::Error, Level::Error.to_level_filter());
1637 assert_eq!(LevelFilter::Trace, Level::Trace.to_level_filter());
1641 fn test_level_filter_as_str() {
1643 (LevelFilter::Off, "OFF"),
1644 (LevelFilter::Error, "ERROR"),
1645 (LevelFilter::Warn, "WARN"),
1646 (LevelFilter::Info, "INFO"),
1647 (LevelFilter::Debug, "DEBUG"),
1648 (LevelFilter::Trace, "TRACE"),
1650 for (input, expected) in tests {
1651 assert_eq!(*expected, input.as_str());
1656 #[cfg(feature = "std")]
1657 fn test_error_trait() {
1658 use super::SetLoggerError;
1659 let e = SetLoggerError(());
1662 "attempted to set a logger after the logging system \
1663 was already initialized"
1668 fn test_metadata_builder() {
1669 use super::MetadataBuilder;
1670 let target = "myApp";
1671 let metadata_test = MetadataBuilder::new()
1672 .level(Level::Debug)
1675 assert_eq!(metadata_test.level(), Level::Debug);
1676 assert_eq!(metadata_test.target(), "myApp");
1680 fn test_metadata_convenience_builder() {
1681 use super::Metadata;
1682 let target = "myApp";
1683 let metadata_test = Metadata::builder()
1684 .level(Level::Debug)
1687 assert_eq!(metadata_test.level(), Level::Debug);
1688 assert_eq!(metadata_test.target(), "myApp");
1692 fn test_record_builder() {
1693 use super::{MetadataBuilder, RecordBuilder};
1694 let target = "myApp";
1695 let metadata = MetadataBuilder::new().target(target).build();
1696 let fmt_args = format_args!("hello");
1697 let record_test = RecordBuilder::new()
1700 .module_path(Some("foo"))
1704 assert_eq!(record_test.metadata().target(), "myApp");
1705 assert_eq!(record_test.module_path(), Some("foo"));
1706 assert_eq!(record_test.file(), Some("bar"));
1707 assert_eq!(record_test.line(), Some(30));
1711 fn test_record_convenience_builder() {
1712 use super::{Metadata, Record};
1713 let target = "myApp";
1714 let metadata = Metadata::builder().target(target).build();
1715 let fmt_args = format_args!("hello");
1716 let record_test = Record::builder()
1719 .module_path(Some("foo"))
1723 assert_eq!(record_test.target(), "myApp");
1724 assert_eq!(record_test.module_path(), Some("foo"));
1725 assert_eq!(record_test.file(), Some("bar"));
1726 assert_eq!(record_test.line(), Some(30));
1730 fn test_record_complete_builder() {
1731 use super::{Level, Record};
1732 let target = "myApp";
1733 let record_test = Record::builder()
1734 .module_path(Some("foo"))
1738 .level(Level::Error)
1740 assert_eq!(record_test.target(), "myApp");
1741 assert_eq!(record_test.level(), Level::Error);
1742 assert_eq!(record_test.module_path(), Some("foo"));
1743 assert_eq!(record_test.file(), Some("bar"));
1744 assert_eq!(record_test.line(), Some(30));
1748 #[cfg(feature = "kv_unstable")]
1749 fn test_record_key_values_builder() {
1751 use kv::{self, Visitor};
1753 struct TestVisitor {
1757 impl<'kvs> Visitor<'kvs> for TestVisitor {
1762 ) -> Result<(), kv::Error> {
1763 self.seen_pairs += 1;
1768 let kvs: &[(&str, i32)] = &[("a", 1), ("b", 2)];
1769 let record_test = Record::builder().key_values(&kvs).build();
1771 let mut visitor = TestVisitor { seen_pairs: 0 };
1773 record_test.key_values().visit(&mut visitor).unwrap();
1775 assert_eq!(2, visitor.seen_pairs);
1779 #[cfg(feature = "kv_unstable")]
1780 fn test_record_key_values_get_coerce() {
1783 let kvs: &[(&str, &str)] = &[("a", "1"), ("b", "2")];
1784 let record = Record::builder().key_values(&kvs).build();
1791 .expect("missing key")
1793 .expect("invalid value")
1797 // Test that the `impl Log for Foo` blocks work
1798 // This test mostly operates on a type level, so failures will be compile errors
1800 fn test_foreign_impl() {
1802 #[cfg(feature = "std")]
1805 fn assert_is_log<T: Log + ?Sized>() {}
1807 assert_is_log::<&dyn Log>();
1809 #[cfg(feature = "std")]
1810 assert_is_log::<Box<dyn Log>>();
1812 #[cfg(feature = "std")]
1813 assert_is_log::<Arc<dyn Log>>();
1815 // Assert these statements for all T: Log + ?Sized
1817 fn forall<T: Log + ?Sized>() {
1818 #[cfg(feature = "std")]
1819 assert_is_log::<Box<T>>();
1821 assert_is_log::<&T>();
1823 #[cfg(feature = "std")]
1824 assert_is_log::<Arc<T>>();