Coverage Report

Created: 2026-07-25 06:12

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