• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #![allow(dead_code, unused_imports)]
2 
3 #[cfg(not(lib_build))]
4 #[macro_use]
5 extern crate log;
6 
7 use log::{Level, LevelFilter, Log, Metadata, Record};
8 use std::sync::{Arc, Mutex};
9 
10 #[cfg(feature = "std")]
11 use log::set_boxed_logger;
12 
13 #[cfg(not(feature = "std"))]
set_boxed_logger(logger: Box<dyn Log>) -> Result<(), log::SetLoggerError>14 fn set_boxed_logger(logger: Box<dyn Log>) -> Result<(), log::SetLoggerError> {
15     log::set_logger(Box::leak(logger))
16 }
17 
18 struct State {
19     last_log: Mutex<Option<Level>>,
20 }
21 
22 struct Logger(Arc<State>);
23 
24 impl Log for Logger {
enabled(&self, _: &Metadata) -> bool25     fn enabled(&self, _: &Metadata) -> bool {
26         true
27     }
28 
log(&self, record: &Record)29     fn log(&self, record: &Record) {
30         *self.0.last_log.lock().unwrap() = Some(record.level());
31     }
flush(&self)32     fn flush(&self) {}
33 }
34 
35 #[cfg_attr(lib_build, test)]
main()36 fn main() {
37     // These tests don't really make sense when static
38     // max level filtering is applied
39     #[cfg(not(any(
40         feature = "max_level_off",
41         feature = "max_level_error",
42         feature = "max_level_warn",
43         feature = "max_level_info",
44         feature = "max_level_debug",
45         feature = "max_level_trace",
46         feature = "release_max_level_off",
47         feature = "release_max_level_error",
48         feature = "release_max_level_warn",
49         feature = "release_max_level_info",
50         feature = "release_max_level_debug",
51         feature = "release_max_level_trace",
52     )))]
53     {
54         let me = Arc::new(State {
55             last_log: Mutex::new(None),
56         });
57         let a = me.clone();
58         set_boxed_logger(Box::new(Logger(me))).unwrap();
59 
60         test(&a, LevelFilter::Off);
61         test(&a, LevelFilter::Error);
62         test(&a, LevelFilter::Warn);
63         test(&a, LevelFilter::Info);
64         test(&a, LevelFilter::Debug);
65         test(&a, LevelFilter::Trace);
66     }
67 }
68 
test(a: &State, filter: LevelFilter)69 fn test(a: &State, filter: LevelFilter) {
70     log::set_max_level(filter);
71     error!("");
72     last(&a, t(Level::Error, filter));
73     warn!("");
74     last(&a, t(Level::Warn, filter));
75     info!("");
76     last(&a, t(Level::Info, filter));
77     debug!("");
78     last(&a, t(Level::Debug, filter));
79     trace!("");
80     last(&a, t(Level::Trace, filter));
81 
82     fn t(lvl: Level, filter: LevelFilter) -> Option<Level> {
83         if lvl <= filter {
84             Some(lvl)
85         } else {
86             None
87         }
88     }
89 }
90 
last(state: &State, expected: Option<Level>)91 fn last(state: &State, expected: Option<Level>) {
92     let lvl = state.last_log.lock().unwrap().take();
93     assert_eq!(lvl, expected);
94 }
95