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