Debian Codegraph @

src/lib.rs

raw symbols SCIP
1 //! A logger that prints all messages with a simple, readable output format.
2 //!
3 //! Optional features include timestamps, colored output and logging to stderr.
4 //!
5 //! ```rust
6 //! simple_logger::SimpleLogger::new().env().init().unwrap();
7 //!
8 //! log::warn!("This is an example message.");
9 //! ```
10 //!
11 //! Some shortcuts are available for common use cases.
12 //!
13 //! Just initialize logging without any configuration:
14 //!
15 //! ```rust
16 //! simple_logger::init().unwrap();
17 //! ```
18 //!
19 //! Set the log level from the `RUST_LOG` environment variable:
20 //!
21 //! ```rust
22 //! simple_logger::init_with_env().unwrap();
23 //! ```
24 //!
25 //! Hardcode a default log level:
26 //!
27 //! ```rust
28 //! simple_logger::init_with_level(log::Level::Warn).unwrap();
29 //! ```
30
31 #![cfg_attr(feature = "nightly", feature(thread_id_value))]
32
33 #[cfg(feature = "colors")]
34 use colored::*;
35 use log::{Level, LevelFilter, Log, Metadata, Record, SetLoggerError};
36 use std::{collections::HashMap, str::FromStr};
37 #[cfg(feature = "timestamps")]
38 use time::{format_description::FormatItem, OffsetDateTime, UtcOffset};
39
40 #[cfg(feature = "timestamps")]
41 const TIMESTAMP_FORMAT_OFFSET: &[FormatItem] = time::macros::format_description!(
42 "[year]-[month]-[day]T[hour]:[minute]:[second].[subsecond digits:3][offset_hour sign:mandatory]:[offset_minute]"
43 );
44
45 #[cfg(feature = "timestamps")]
46 const TIMESTAMP_FORMAT_UTC: &[FormatItem] =
47 time::macros::format_description!("[year]-[month]-[day]T[hour]:[minute]:[second].[subsecond digits:3]Z");
48
49 #[cfg(feature = "timestamps")]
50 #[derive(PartialEq)]
51 enum Timestamps {
52 None,
53 Local,
54 Utc,
55 UtcOffset(UtcOffset),
56 }
57
58 /// Implements [`Log`] and a set of simple builder methods for configuration.
59 ///
60 /// Use the various "builder" methods on this struct to configure the logger,
61 /// then call [`init`] to configure the [`log`] crate.
62 pub struct SimpleLogger {
63 /// The default logging level
64 default_level: LevelFilter,
65
66 /// The specific logging level for each module
67 ///
68 /// This is used to override the default value for some specific modules.
69 ///
70 /// This must be sorted from most-specific to least-specific, so that [`enabled`](#method.enabled) can scan the
71 /// vector for the first match to give us the desired log level for a module.
72 module_levels: Vec<(String, LevelFilter)>,
73
74 /// Whether to include thread names (and IDs) or not
75 ///
76 /// This field is only available if the `threads` feature is enabled.
77 #[cfg(feature = "threads")]
78 threads: bool,
79
80 /// Control how timestamps are displayed.
81 ///
82 /// This field is only available if the `timestamps` feature is enabled.
83 #[cfg(feature = "timestamps")]
84 timestamps: Timestamps,
85 #[cfg(feature = "timestamps")]
86 timestamps_format: Option<&'static [FormatItem<'static>]>,
87
88 /// Whether to use color output or not.
89 ///
90 /// This field is only available if the `color` feature is enabled.
91 #[cfg(feature = "colors")]
92 colors: bool,
93 }
94
95 impl SimpleLogger {
96 /// Initializes the global logger with a SimpleLogger instance with
97 /// default log level set to `Level::Trace`.
98 ///
99 /// ```no_run
100 /// use simple_logger::SimpleLogger;
101 /// SimpleLogger::new().env().init().unwrap();
102 /// log::warn!("This is an example message.");
103 /// ```
104 ///
105 /// [`init`]: #method.init
106 #[must_use = "You must call init() to begin logging"]
107 pub fn new() -> SimpleLogger {
108 SimpleLogger {
109 default_level: LevelFilter::Trace,
110 module_levels: Vec::new(),
111
112 #[cfg(feature = "threads")]
113 threads: false,
114
115 #[cfg(feature = "timestamps")]
116 timestamps: Timestamps::Utc,
117
118 #[cfg(feature = "timestamps")]
119 timestamps_format: None,
120
121 #[cfg(feature = "colors")]
122 colors: true,
123 }
124 }
125
126 /// Initializes the global logger with log level read from `RUST_LOG` environment
127 /// variable value. Deprecated in favor of `env()`.
128 ///
129 /// You may use the various builder-style methods on this type to configure
130 /// the logger, and you must call [`init`] in order to start logging messages.
131 ///
132 /// ```no_run
133 /// use simple_logger::SimpleLogger;
134 /// SimpleLogger::from_env().init().unwrap();
135 /// log::warn!("This is an example message.");
136 /// ```
137 ///
138 /// [`init`]: #method.init
139 #[must_use = "You must call init() to begin logging"]
140 #[deprecated(
141 since = "1.12.0",
142 note = "Use [`env`](#method.env) instead. Will be removed in version 2.0.0."
143 )]
144 pub fn from_env() -> SimpleLogger {
145 SimpleLogger::new().with_level(log::LevelFilter::Error).env()
146 }
147
148 /// Enables the user to choose log level by setting `RUST_LOG=<level>`
149 /// environment variable. This will use the default level set by
150 /// [`with_level`] if `RUST_LOG` is not set or can't be parsed as a
151 /// standard log level.
152 ///
153 /// This must be called after [`with_level`]. If called before
154 /// [`with_level`], it will have no effect.
155 ///
156 /// [`with_level`]: #method.with_level
157 #[must_use = "You must call init() to begin logging"]
158 pub fn env(mut self) -> SimpleLogger {
159 self.default_level = std::env::var("RUST_LOG")
160 .ok()
161 .as_deref()
162 .map(log::LevelFilter::from_str)
163 .and_then(Result::ok)
164 .unwrap_or(self.default_level);
165
166 self
167 }
168
169 /// Set the 'default' log level.
170 ///
171 /// You can override the default level for specific modules and their sub-modules using [`with_module_level`]
172 ///
173 /// This must be called before [`env`]. If called after [`env`], it will override the value loaded from the environment.
174 ///
175 /// [`env`]: #method.env
176 /// [`with_module_level`]: #method.with_module_level
177 #[must_use = "You must call init() to begin logging"]
178 pub fn with_level(mut self, level: LevelFilter) -> SimpleLogger {
179 self.default_level = level;
180 self
181 }
182
183 /// Override the log level for some specific modules.
184 ///
185 /// This sets the log level of a specific module and all its sub-modules.
186 /// When both the level for a parent module as well as a child module are set,
187 /// the more specific value is taken. If the log level for the same module is
188 /// specified twice, the resulting log level is implementation defined.
189 ///
190 /// # Examples
191 ///
192 /// Silence an overly verbose crate:
193 ///
194 /// ```no_run
195 /// use simple_logger::SimpleLogger;
196 /// use log::LevelFilter;
197 ///
198 /// SimpleLogger::new().with_module_level("chatty_dependency", LevelFilter::Warn).init().unwrap();
199 /// ```
200 ///
201 /// Disable logging for all dependencies:
202 ///
203 /// ```no_run
204 /// use simple_logger::SimpleLogger;
205 /// use log::LevelFilter;
206 ///
207 /// SimpleLogger::new()
208 /// .with_level(LevelFilter::Off)
209 /// .with_module_level("my_crate", LevelFilter::Info)
210 /// .init()
211 /// .unwrap();
212 /// ```
213 //
214 // This method *must* sort `module_levels` for the [`enabled`](#method.enabled) method to work correctly.
215 #[must_use = "You must call init() to begin logging"]
216 pub fn with_module_level(mut self, target: &str, level: LevelFilter) -> SimpleLogger {
217 self.module_levels.push((target.to_string(), level));
218 self.module_levels
219 .sort_by_key(|(name, _level)| name.len().wrapping_neg());
220 self
221 }
222
223 /// Override the log level for specific targets.
224 // This method *must* sort `module_levels` for the [`enabled`](#method.enabled) method to work correctly.
225 #[must_use = "You must call init() to begin logging"]
226 #[deprecated(
227 since = "1.11.0",
228 note = "Use [`with_module_level`](#method.with_module_level) instead. Will be removed in version 2.0.0."
229 )]
230 pub fn with_target_levels(mut self, target_levels: HashMap<String, LevelFilter>) -> SimpleLogger {
231 self.module_levels = target_levels.into_iter().collect();
232 self.module_levels
233 .sort_by_key(|(name, _level)| name.len().wrapping_neg());
234 self
235 }
236
237 /// Control whether thread names (and IDs) are printed or not.
238 ///
239 /// This method is only available if the `threads` feature is enabled.
240 /// Thread names are disabled by default.
241 #[must_use = "You must call init() to begin logging"]
242 #[cfg(feature = "threads")]
243 pub fn with_threads(mut self, threads: bool) -> SimpleLogger {
244 self.threads = threads;
245 self
246 }
247
248 /// Control whether timestamps are printed or not.
249 ///
250 /// Timestamps will be displayed in the local timezone.
251 ///
252 /// This method is only available if the `timestamps` feature is enabled.
253 #[must_use = "You must call init() to begin logging"]
254 #[cfg(feature = "timestamps")]
255 #[deprecated(
256 since = "1.16.0",
257 note = "Use [`with_local_timestamps`] or [`with_utc_timestamps`] instead. Will be removed in version 2.0.0."
258 )]
259 pub fn with_timestamps(mut self, timestamps: bool) -> SimpleLogger {
260 if timestamps {
261 self.timestamps = Timestamps::Local
262 } else {
263 self.timestamps = Timestamps::None
264 }
265 self
266 }
267
268 /// Control the format used for timestamps.
269 ///
270 /// Without this, a default format is used depending on the timestamps type.
271 ///
272 /// The syntax for the format_description macro can be found in the
273 /// [`time` crate book](https://time-rs.github.io/book/api/format-description.html).
274 ///
275 /// ```
276 /// simple_logger::SimpleLogger::new()
277 /// .with_level(log::LevelFilter::Debug)
278 /// .env()
279 /// .with_timestamp_format(time::macros::format_description!("[year]-[month]-[day] [hour]:[minute]:[second]"))
280 /// .init()
281 /// .unwrap();
282 /// ```
283 #[must_use = "You must call init() to begin logging"]
284 #[cfg(feature = "timestamps")]
285 pub fn with_timestamp_format(mut self, format: &'static [FormatItem<'static>]) -> SimpleLogger {
286 self.timestamps_format = Some(format);
287 self
288 }
289
290 /// Don't display any timestamps.
291 ///
292 /// This method is only available if the `timestamps` feature is enabled.
293 #[must_use = "You must call init() to begin logging"]
294 #[cfg(feature = "timestamps")]
295 pub fn without_timestamps(mut self) -> SimpleLogger {
296 self.timestamps = Timestamps::None;
297 self
298 }
299
300 /// Display timestamps using the local timezone.
301 ///
302 /// This method is only available if the `timestamps` feature is enabled.
303 #[must_use = "You must call init() to begin logging"]
304 #[cfg(feature = "timestamps")]
305 pub fn with_local_timestamps(mut self) -> SimpleLogger {
306 self.timestamps = Timestamps::Local;
307 self
308 }
309
310 /// Display timestamps using UTC.
311 ///
312 /// This method is only available if the `timestamps` feature is enabled.
313 #[must_use = "You must call init() to begin logging"]
314 #[cfg(feature = "timestamps")]
315 pub fn with_utc_timestamps(mut self) -> SimpleLogger {
316 self.timestamps = Timestamps::Utc;
317 self
318 }
319
320 /// Display timestamps using a static UTC offset.
321 ///
322 /// This method is only available if the `timestamps` feature is enabled.
323 #[must_use = "You must call init() to begin logging"]
324 #[cfg(feature = "timestamps")]
325 pub fn with_utc_offset(mut self, offset: UtcOffset) -> SimpleLogger {
326 self.timestamps = Timestamps::UtcOffset(offset);
327 self
328 }
329
330 /// Control whether messages are colored or not.
331 ///
332 /// This method is only available if the `colored` feature is enabled.
333 #[must_use = "You must call init() to begin logging"]
334 #[cfg(feature = "colors")]
335 pub fn with_colors(mut self, colors: bool) -> SimpleLogger {
336 self.colors = colors;
337 self
338 }
339
340 /// Configure the logger
341 pub fn max_level(&self) -> LevelFilter {
342 let max_level = self.module_levels.iter().map(|(_name, level)| level).copied().max();
343 max_level
344 .map(|lvl| lvl.max(self.default_level))
345 .unwrap_or(self.default_level)
346 }
347
348 /// 'Init' the actual logger and instantiate it,
349 /// this method MUST be called in order for the logger to be effective.
350 pub fn init(self) -> Result<(), SetLoggerError> {
351 #[cfg(all(windows, feature = "colored"))]
352 set_up_windows_color_terminal();
353
354 #[cfg(all(feature = "colored", feature = "stderr"))]
355 use_stderr_for_colors();
356
357 log::set_max_level(self.max_level());
358 log::set_boxed_logger(Box::new(self))
359 }
360 }
361
362 impl Default for SimpleLogger {
363 /// See [this](struct.SimpleLogger.html#method.new)
364 fn default() -> Self {
365 SimpleLogger::new()
366 }
367 }
368
369 impl Log for SimpleLogger {
370 fn enabled(&self, metadata: &Metadata) -> bool {
371 &metadata.level().to_level_filter()
372 <= self
373 .module_levels
374 .iter()
375 /* At this point the Vec is already sorted so that we can simply take
376 * the first match
377 */
378 .find(|(name, _level)| metadata.target().starts_with(name))
379 .map(|(_name, level)| level)
380 .unwrap_or(&self.default_level)
381 }
382
383 fn log(&self, record: &Record) {
384 if self.enabled(record.metadata()) {
385 let level_string = {
386 #[cfg(feature = "colors")]
387 {
388 if self.colors {
389 match record.level() {
390 Level::Error => format!("{:<5}", record.level().to_string()).red().to_string(),
391 Level::Warn => format!("{:<5}", record.level().to_string()).yellow().to_string(),
392 Level::Info => format!("{:<5}", record.level().to_string()).cyan().to_string(),
393 Level::Debug => format!("{:<5}", record.level().to_string()).purple().to_string(),
394 Level::Trace => format!("{:<5}", record.level().to_string()).normal().to_string(),
395 }
396 } else {
397 format!("{:<5}", record.level().to_string())
398 }
399 }
400 #[cfg(not(feature = "colors"))]
401 {
402 format!("{:<5}", record.level().to_string())
403 }
404 };
405
406 let target = if !record.target().is_empty() {
407 record.target()
408 } else {
409 record.module_path().unwrap_or_default()
410 };
411
412 let thread = {
413 #[cfg(feature = "threads")]
414 if self.threads {
415 let thread = std::thread::current();
416
417 format!("@{}", {
418 #[cfg(feature = "nightly")]
419 {
420 thread.name().unwrap_or(&thread.id().as_u64().to_string())
421 }
422
423 #[cfg(not(feature = "nightly"))]
424 {
425 thread.name().unwrap_or("?")
426 }
427 })
428 } else {
429 "".to_string()
430 }
431
432 #[cfg(not(feature = "threads"))]
433 ""
434 };
435
436 let timestamp = {
437 #[cfg(feature = "timestamps")]
438 match self.timestamps {
439 Timestamps::None => "".to_string(),
440 Timestamps::Local => format!(
441 "{} ",
442 OffsetDateTime::now_local()
443 .expect(concat!(
444 "Could not determine the UTC offset on this system. ",
445 "Consider displaying UTC time instead. ",
446 "Possible causes are that the time crate does not implement \"local_offset_at\" ",
447 "on your system, or that you are running in a multi-threaded environment and ",
448 "the time crate is returning \"None\" from \"local_offset_at\" to avoid unsafe ",
449 "behaviour. See the time crate's documentation for more information. ",
450 "(https://time-rs.github.io/internal-api/time/index.html#feature-flags)"
451 ))
452 .format(&self.timestamps_format.unwrap_or(TIMESTAMP_FORMAT_OFFSET))
453 .unwrap()
454 ),
455 Timestamps::Utc => format!(
456 "{} ",
457 OffsetDateTime::now_utc()
458 .format(&self.timestamps_format.unwrap_or(TIMESTAMP_FORMAT_UTC))
459 .unwrap()
460 ),
461 Timestamps::UtcOffset(offset) => format!(
462 "{} ",
463 OffsetDateTime::now_utc()
464 .to_offset(offset)
465 .format(&self.timestamps_format.unwrap_or(TIMESTAMP_FORMAT_OFFSET))
466 .unwrap()
467 ),
468 }
469
470 #[cfg(not(feature = "timestamps"))]
471 ""
472 };
473
474 let message = format!("{}{} [{}{}] {}", timestamp, level_string, target, thread, record.args());
475
476 #[cfg(not(feature = "stderr"))]
477 println!("{}", message);
478
479 #[cfg(feature = "stderr")]
480 eprintln!("{}", message);
481 }
482 }
483
484 fn flush(&self) {}
485 }
486
487 /// Configure the console to display colours.
488 ///
489 /// This is only needed on Windows when using the 'colors' feature.
490 /// It doesn't currently handle combining the 'colors' and 'stderr' features.
491 #[cfg(all(windows, feature = "colors"))]
492 pub fn set_up_windows_color_terminal() {
493 use std::io::{stdout, IsTerminal};
494
495 if stdout().is_terminal() {
496 unsafe {
497 use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
498 use windows_sys::Win32::System::Console::{
499 GetConsoleMode, GetStdHandle, SetConsoleMode, CONSOLE_MODE, ENABLE_VIRTUAL_TERMINAL_PROCESSING,
500 STD_OUTPUT_HANDLE,
501 };
502
503 let stdout = GetStdHandle(STD_OUTPUT_HANDLE);
504
505 if stdout == INVALID_HANDLE_VALUE {
506 return;
507 }
508
509 let mut mode: CONSOLE_MODE = 0;
510
511 if GetConsoleMode(stdout, &mut mode) == 0 {
512 return;
513 }
514
515 SetConsoleMode(stdout, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
516 }
517 }
518 }
519
520 /// The colored crate will disable colors when STDOUT is not a terminal. This method overrides this
521 /// behaviour to check the status of STDERR instead.
522 #[cfg(all(feature = "colored", feature = "stderr"))]
523 fn use_stderr_for_colors() {
524 use std::io::{stderr, IsTerminal};
525
526 colored::control::set_override(stderr().is_terminal());
527 }
528
529 /// Initialise the logger with its default configuration.
530 ///
531 /// Log messages will not be filtered.
532 /// The `RUST_LOG` environment variable is not used.
533 pub fn init() -> Result<(), SetLoggerError> {
534 SimpleLogger::new().init()
535 }
536
537 /// Initialise the logger with its default configuration.
538 ///
539 /// Log messages will not be filtered.
540 /// The `RUST_LOG` environment variable is not used.
541 ///
542 /// This function is only available if the `timestamps` feature is enabled.
543 #[cfg(feature = "timestamps")]
544 pub fn init_utc() -> Result<(), SetLoggerError> {
545 SimpleLogger::new().with_utc_timestamps().init()
546 }
547
548 /// Initialise the logger with the `RUST_LOG` environment variable.
549 ///
550 /// Log messages will be filtered based on the `RUST_LOG` environment variable.
551 ///
552 /// This will use the default level ([`LevelFilter::Trace`]) if the `RUST_LOG`
553 /// environment variable is not set or can't be parsed as a standard log level
554 /// (see [`LevelFilter::from_str`] and [`log::LOG_LEVEL_NAMES`] for valid
555 /// names).
556 pub fn init_with_env() -> Result<(), SetLoggerError> {
557 SimpleLogger::new().env().init()
558 }
559
560 /// Initialise the logger with a specific log level.
561 ///
562 /// Log messages below the given [`Level`] will be filtered.
563 /// The `RUST_LOG` environment variable is not used.
564 pub fn init_with_level(level: Level) -> Result<(), SetLoggerError> {
565 SimpleLogger::new().with_level(level.to_level_filter()).init()
566 }
567
568 /// Use [`init_with_env`] instead.
569 ///
570 /// This does the same as [`init_with_env`] but unwraps the result.
571 #[deprecated(
572 since = "1.12.0",
573 note = "Use [`init_with_env`] instead, which does not unwrap the result. Will be removed in version 2.0.0."
574 )]
575 pub fn init_by_env() {
576 init_with_env().unwrap()
577 }
578
579 #[cfg(test)]
580 mod test {
581 use super::*;
582
583 #[test]
584 fn test_module_levels_allowlist() {
585 let logger = SimpleLogger::new()
586 .with_level(LevelFilter::Off)
587 .with_module_level("my_crate", LevelFilter::Info);
588
589 assert!(logger.enabled(&create_log("my_crate", Level::Info)));
590 assert!(logger.enabled(&create_log("my_crate::module", Level::Info)));
591 assert!(!logger.enabled(&create_log("my_crate::module", Level::Debug)));
592 assert!(!logger.enabled(&create_log("not_my_crate", Level::Debug)));
593 assert!(!logger.enabled(&create_log("not_my_crate::module", Level::Error)));
594 }
595
596 #[test]
597 fn test_module_levels_denylist() {
598 let logger = SimpleLogger::new()
599 .with_level(LevelFilter::Debug)
600 .with_module_level("my_crate", LevelFilter::Trace)
601 .with_module_level("chatty_dependency", LevelFilter::Info);
602
603 assert!(logger.enabled(&create_log("my_crate", Level::Info)));
604 assert!(logger.enabled(&create_log("my_crate", Level::Trace)));
605 assert!(logger.enabled(&create_log("my_crate::module", Level::Info)));
606 assert!(logger.enabled(&create_log("my_crate::module", Level::Trace)));
607 assert!(logger.enabled(&create_log("not_my_crate", Level::Debug)));
608 assert!(!logger.enabled(&create_log("not_my_crate::module", Level::Trace)));
609 assert!(logger.enabled(&create_log("chatty_dependency", Level::Info)));
610 assert!(!logger.enabled(&create_log("chatty_dependency", Level::Debug)));
611 assert!(!logger.enabled(&create_log("chatty_dependency::module", Level::Debug)));
612 assert!(logger.enabled(&create_log("chatty_dependency::module", Level::Warn)));
613 }
614
615 /// Test that enabled() looks for the most specific target.
616 #[test]
617 fn test_module_levels() {
618 let logger = SimpleLogger::new()
619 .with_level(LevelFilter::Off)
620 .with_module_level("a", LevelFilter::Off)
621 .with_module_level("a::b::c", LevelFilter::Off)
622 .with_module_level("a::b", LevelFilter::Info);
623
624 assert_eq!(logger.enabled(&create_log("a", Level::Info)), false);
625 assert_eq!(logger.enabled(&create_log("a::b", Level::Info)), true);
626 assert_eq!(logger.enabled(&create_log("a::b::c", Level::Info)), false);
627 }
628
629 #[test]
630 fn test_max_level() {
631 let builder = SimpleLogger::new();
632 assert_eq!(builder.max_level(), LevelFilter::Trace);
633 }
634
635 #[test]
636 #[cfg(feature = "timestamps")]
637 fn test_timestamps_defaults() {
638 let builder = SimpleLogger::new();
639 assert!(builder.timestamps == Timestamps::Utc);
640 }
641
642 #[test]
643 #[cfg(feature = "timestamps")]
644 #[allow(deprecated)]
645 fn test_with_timestamps() {
646 let builder = SimpleLogger::new().with_timestamps(false);
647 assert!(builder.timestamps == Timestamps::None);
648 }
649
650 #[test]
651 #[cfg(feature = "timestamps")]
652 fn test_with_utc_timestamps() {
653 let builder = SimpleLogger::new().with_utc_timestamps();
654 assert!(builder.timestamps == Timestamps::Utc);
655 }
656
657 #[test]
658 #[cfg(feature = "timestamps")]
659 fn test_with_local_timestamps() {
660 let builder = SimpleLogger::new().with_local_timestamps();
661 assert!(builder.timestamps == Timestamps::Local);
662 }
663
664 #[test]
665 #[cfg(feature = "timestamps")]
666 #[allow(deprecated)]
667 fn test_with_timestamps_format() {
668 let builder =
669 SimpleLogger::new().with_timestamp_format(time::macros::format_description!("[hour]:[minute]:[second]"));
670 assert!(builder.timestamps_format.is_some());
671 }
672
673 #[test]
674 #[cfg(feature = "colored")]
675 fn test_with_colors() {
676 let mut builder = SimpleLogger::new();
677 assert!(builder.colors == true);
678
679 builder = builder.with_colors(false);
680 assert!(builder.colors == false);
681 }
682
683 /// > And, without sorting, this would lead to all serde_json logs being treated as if they were configured to
684 /// > Error level instead of Trace (since to determine the logging level for target, the code finds first match in
685 /// > module_levels by a string prefix).
686 #[test]
687 fn test_issue_90() {
688 let logger = SimpleLogger::new()
689 .with_level(LevelFilter::Off)
690 .with_module_level("serde", LevelFilter::Error)
691 .with_module_level("serde_json", LevelFilter::Trace);
692
693 assert_eq!(logger.enabled(&create_log("serde", Level::Trace)), false);
694 assert_eq!(logger.enabled(&create_log("serde_json", Level::Trace)), true);
695 }
696
697 fn create_log(name: &str, level: Level) -> Metadata<'_> {
698 let mut builder = Metadata::builder();
699 builder.level(level);
700 builder.target(name);
701 builder.build()
702 }
703 }