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