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