Skip to main content

bpi_rs/
log.rs

1use std::fmt;
2use std::time::{Duration, SystemTime, UNIX_EPOCH};
3use tracing_subscriber::fmt::format::Writer;
4use tracing_subscriber::fmt::time::FormatTime;
5
6pub struct TimeFormat;
7
8impl FormatTime for TimeFormat {
9    fn format_time(&self, w: &mut Writer<'_>) -> fmt::Result {
10        let now = SystemTime::now()
11            .duration_since(UNIX_EPOCH)
12            .unwrap_or(Duration::ZERO);
13
14        // 转换为中国时区 (UTC+8)
15        let china_time = now + Duration::from_secs(8 * 3600);
16        let total_seconds = china_time.as_secs();
17
18        // 计算日期和时间
19        let days_since_epoch = total_seconds / 86400;
20        let seconds_today = total_seconds % 86400;
21
22        let hours = (seconds_today / 3600) % 24;
23        let minutes = (seconds_today / 60) % 60;
24        let seconds = seconds_today % 60;
25
26        // 计算月份和日期 (简化版本,1970年1月1日开始)
27        let (month, day) = days_to_month_day(days_since_epoch);
28
29        // 灰色时间
30        write!(
31            w,
32            "\x1b[90m{:02}-{:02} {:02}:{:02}:{:02}\x1b[0m",
33            month, day, hours, minutes, seconds
34        )
35    }
36}
37
38// 简化的日期计算函数
39fn days_to_month_day(days: u64) -> (u32, u32) {
40    // 这是一个简化版本,基于平均月份长度
41    // 对于生产环境,建议使用更精确的日期计算
42    let year_days = days % 365;
43    let month = ((year_days * 12) / 365) + 1;
44    let day = (year_days % 30) + 1;
45    (month as u32, day as u32)
46}
47
48pub fn init_log() {
49    let _ = tracing_subscriber::fmt()
50        .with_timer(TimeFormat)
51        .with_target(false)
52        .compact()
53        .try_init();
54}