xref: /aosp_15_r20/external/flashrom/util/flashrom_tester/src/logger.rs (revision 0d6140be3aa665ecc836e8907834fcd3e3b018fc)
1 //
2 // Copyright 2019, Google Inc.
3 // All rights reserved.
4 //
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are
7 // met:
8 //
9 //    * Redistributions of source code must retain the above copyright
10 // notice, this list of conditions and the following disclaimer.
11 //    * Redistributions in binary form must reproduce the above
12 // copyright notice, this list of conditions and the following disclaimer
13 // in the documentation and/or other materials provided with the
14 // distribution.
15 //    * Neither the name of Google Inc. nor the names of its
16 // contributors may be used to endorse or promote products derived from
17 // this software without specific prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 //
31 // Alternatively, this software may be distributed under the terms of the
32 // GNU General Public License ("GPL") version 2 as published by the Free
33 // Software Foundation.
34 //
35 
36 use flashrom_tester::types;
37 use std::io::Write;
38 
39 struct Logger {
40     level: log::LevelFilter,
41     color: types::Color,
42 }
43 
44 impl log::Log for Logger {
enabled(&self, metadata: &log::Metadata) -> bool45     fn enabled(&self, metadata: &log::Metadata) -> bool {
46         metadata.level() <= self.level
47     }
48 
log(&self, record: &log::Record)49     fn log(&self, record: &log::Record) {
50         // Write errors deliberately ignored
51         let stdout = std::io::stdout();
52         let mut lock = stdout.lock();
53         let now = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Micros, true);
54         let _ = write!(lock, "{}{} ", self.color.magenta, now);
55         let _ = write!(
56             lock,
57             "{}[ {} ]{} ",
58             self.color.yellow,
59             record.level(),
60             self.color.reset
61         );
62         let _ = writeln!(lock, "{}", record.args());
63     }
64 
flush(&self)65     fn flush(&self) {
66         // Flush errors deliberately ignored
67         let _ = std::io::stdout().flush();
68     }
69 }
70 
init(debug: bool)71 pub fn init(debug: bool) {
72     let mut logger = Logger {
73         level: log::LevelFilter::Info,
74         color: if atty::is(atty::Stream::Stdout) {
75             types::COLOR
76         } else {
77             types::NOCOLOR
78         },
79     };
80 
81     if debug {
82         logger.level = log::LevelFilter::Debug;
83     }
84     log::set_max_level(logger.level);
85     log::set_boxed_logger(Box::new(logger)).unwrap();
86 }
87 
88 #[cfg(test)]
89 mod tests {
90     use std::io::Read;
91 
92     use super::Logger;
93     use flashrom_tester::types;
94     use log::{Level, LevelFilter, Log, Record};
95 
run_records(records: &[Record]) -> String96     fn run_records(records: &[Record]) -> String {
97         let buf = gag::BufferRedirect::stdout().unwrap();
98         {
99             let logger = Logger {
100                 level: LevelFilter::Info,
101                 color: types::COLOR,
102             };
103 
104             for record in records {
105                 if logger.enabled(record.metadata()) {
106                     logger.log(record);
107                 }
108             }
109         }
110         let mut ret = String::new();
111         buf.into_inner().read_to_string(&mut ret).unwrap();
112         ret
113     }
114 
115     /// Log messages have the expected format
116     #[test]
format()117     fn format() {
118         let buf = run_records(&[Record::builder()
119             .args(format_args!("Test message at INFO"))
120             .level(Level::Info)
121             .build()]);
122 
123         assert_eq!(&buf[..5], "\x1b[35m");
124         // Time is difficult to test, assume it's formatted okay
125         // Split on the UTC timezone char
126         assert_eq!(
127             buf.split_once("Z ").unwrap().1,
128             "\x1b[33m[ INFO ]\x1b[0m Test message at INFO\n"
129         );
130     }
131 
132     #[test]
level_filter()133     fn level_filter() {
134         let buf = run_records(&[
135             Record::builder()
136                 .args(format_args!("Test message at DEBUG"))
137                 .level(Level::Debug)
138                 .build(),
139             Record::builder()
140                 .args(format_args!("Hello, world!"))
141                 .level(Level::Error)
142                 .build(),
143         ]);
144 
145         // There is one line because the Debug record wasn't written.
146         println!("{}", buf);
147         assert_eq!(buf.lines().count(), 1);
148     }
149 }
150