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