phper_test/log.rs
1// Copyright (c) 2025 PHPER Framework Team
2// PHPER is licensed under Mulan PSL v2.
3// You can use this software according to the terms and conditions of the Mulan
4// PSL v2. You may obtain a copy of Mulan PSL v2 at:
5// http://license.coscl.org.cn/MulanPSL2
6// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY
7// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
8// NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
9// See the Mulan PSL v2 for more details.
10
11//! Logging utilities for phper tests.
12//!
13//! This module provides a centralized logging setup specifically designed for
14//! test environments. It configures the env_logger with custom formatting to
15//! display key-value pairs in a structured format.
16
17use env_logger::fmt::Formatter;
18use log::kv::{self, Key, Value};
19use std::sync::Once;
20
21/// Sets up the logger for test environments.
22///
23/// This function initializes the env_logger with custom formatting that
24/// displays key-value pairs in a structured format with separators. The setup
25/// is guaranteed to run only once using `std::sync::Once`.
26///
27/// # Features
28/// - Uses default environment configuration
29/// - Enables test mode formatting
30/// - Custom key-value formatter that displays each pair with visual separators
31pub fn setup() {
32 static ONCE: Once = Once::new();
33 ONCE.call_once(|| {
34 env_logger::Builder::from_default_env()
35 .default_format()
36 .is_test(true)
37 .format_key_values(|buf, args| {
38 use std::io::Write as _;
39
40 /// A visitor implementation for formatting key-value pairs.
41 ///
42 /// This visitor formats each key-value pair with visual
43 /// separators, making log output more readable
44 /// in test environments.
45 struct Visitor<'a>(&'a mut Formatter);
46
47 impl<'kvs> kv::VisitSource<'kvs> for Visitor<'kvs> {
48 /// Visits and formats a single key-value pair.
49 ///
50 /// # Arguments
51 /// * `key` - The key of the key-value pair
52 /// * `value` - The value of the key-value pair
53 ///
54 /// # Returns
55 /// Returns `Ok(())` on successful formatting, or a
56 /// `kv::Error` if formatting fails.
57 fn visit_pair(
58 &mut self, key: Key<'kvs>, value: Value<'kvs>,
59 ) -> Result<(), kv::Error> {
60 writeln!(self.0).unwrap();
61 writeln!(self.0, "===== {} =====", key).unwrap();
62 writeln!(self.0, "{}", value).unwrap();
63 Ok(())
64 }
65 }
66 args.visit(&mut Visitor(buf)).unwrap();
67 Ok(())
68 })
69 .init();
70 });
71}