apache_avro_test_helper/
logger.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use crate::LOG_MESSAGES;
19use log::{LevelFilter, Log, Metadata};
20use std::sync::OnceLock;
21
22struct TestLogger {
23    delegate: env_logger::Logger,
24}
25
26impl Log for TestLogger {
27    #[inline]
28    fn enabled(&self, _metadata: &Metadata) -> bool {
29        true
30    }
31
32    fn log(&self, record: &log::Record) {
33        if self.enabled(record.metadata()) {
34            LOG_MESSAGES.with(|msgs| msgs.borrow_mut().push(format!("{}", record.args())));
35
36            self.delegate.log(record);
37        }
38    }
39
40    fn flush(&self) {}
41}
42
43fn test_logger() -> &'static TestLogger {
44    // Lazy static because the Logger has to be 'static
45    static TEST_LOGGER_ONCE: OnceLock<TestLogger> = OnceLock::new();
46    TEST_LOGGER_ONCE.get_or_init(|| TestLogger {
47        delegate: env_logger::Builder::from_default_env()
48            .filter_level(LevelFilter::Off)
49            .parse_default_env()
50            .build(),
51    })
52}
53
54pub fn clear_log_messages() {
55    LOG_MESSAGES.with(|msgs| match msgs.try_borrow_mut() {
56        Ok(mut log_messages) => log_messages.clear(),
57        Err(err) => panic!("Failed to clear log messages: {err:?}"),
58    });
59}
60
61pub fn assert_not_logged(unexpected_message: &str) {
62    LOG_MESSAGES.with(|msgs| match msgs.borrow().last() {
63        Some(last_log) if last_log == unexpected_message => {
64            panic!("The following log message should not have been logged: '{unexpected_message}'")
65        }
66        _ => (),
67    });
68}
69
70pub fn assert_logged(expected_message: &str) {
71    let mut deleted = false;
72    LOG_MESSAGES.with(|msgs| {
73        msgs.borrow_mut().retain(|msg| {
74            if msg == expected_message {
75                deleted = true;
76                false
77            } else {
78                true
79            }
80        })
81    });
82
83    if !deleted {
84        panic!("Expected log message has not been logged: '{expected_message}'");
85    }
86}
87
88#[cfg(not(target_arch = "wasm32"))]
89pub(crate) fn install() {
90    log::set_logger(test_logger())
91        .map(|_| log::set_max_level(LevelFilter::Trace))
92        .map_err(|err| {
93            eprintln!("Failed to set the custom logger: {err:?}");
94        })
95        .unwrap();
96}