team-ljyzipelo

공개
159줄4.8 KB
1//! 앱 로그. 표준 오류로 한 줄씩 남김.
2//!
3//! 디버그 빌드(debug_assertions)는 모든 단계(trace까지)를 자세히 남기고,
4//! 배포(릴리스) 빌드는 오류만 남겨 로그를 최소화함. 문제를 조사할 때는
5//! ZIPELO_LOG 환경 변수(off, error, warn, info, debug, trace)로 단계를 바꿀 수 있음.
6//! 암호와 파일 내용은 어느 단계에서도 남기지 않음.
7
8use std::sync::OnceLock;
9use std::time::Instant;
10
11#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
12pub enum Level {
13 Off = 0,
14 Error = 1,
15 Warn = 2,
16 Info = 3,
17 Debug = 4,
18 Trace = 5,
19}
20
21impl Level {
22 fn label(self) -> &'static str {
23 match self {
24 Level::Off => "OFF",
25 Level::Error => "ERROR",
26 Level::Warn => "WARN",
27 Level::Info => "INFO",
28 Level::Debug => "DEBUG",
29 Level::Trace => "TRACE",
30 }
31 }
32
33 /// 빌드 종류에 따른 기본 단계.
34 pub const fn default_for_build() -> Self {
35 if cfg!(debug_assertions) {
36 Level::Trace
37 } else {
38 Level::Error
39 }
40 }
41
42 pub fn parse(text: &str) -> Option<Self> {
43 Some(match text.trim().to_ascii_lowercase().as_str() {
44 "off" | "none" | "0" => Level::Off,
45 "error" | "1" => Level::Error,
46 "warn" | "warning" | "2" => Level::Warn,
47 "info" | "3" => Level::Info,
48 "debug" | "4" => Level::Debug,
49 "trace" | "all" | "5" => Level::Trace,
50 _ => return None,
51 })
52 }
53}
54
55struct State {
56 level: Level,
57 started: Instant,
58}
59
60fn state() -> &'static State {
61 static STATE: OnceLock<State> = OnceLock::new();
62 STATE.get_or_init(|| State {
63 level: std::env::var("ZIPELO_LOG")
64 .ok()
65 .and_then(|value| Level::parse(&value))
66 .unwrap_or(Level::default_for_build()),
67 started: Instant::now(),
68 })
69}
70
71/// 현재 로그 단계.
72pub fn level() -> Level {
73 state().level
74}
75
76/// 이 단계의 로그를 남기는지. 메시지를 만드는 비용을 아낄 때 씀.
77pub fn enabled(level: Level) -> bool {
78 level != Level::Off && level <= state().level
79}
80
81#[doc(hidden)]
82pub fn write(level: Level, target: &str, message: std::fmt::Arguments<'_>) {
83 if !enabled(level) {
84 return;
85 }
86 let elapsed = state().started.elapsed();
87 let thread = std::thread::current();
88 let line = format!(
89 "[{:>5}.{:03}s {:<5} {target} {}] {message}\n",
90 elapsed.as_secs(),
91 elapsed.subsec_millis(),
92 level.label(),
93 thread.name().unwrap_or("-"),
94 );
95 // 표준 오류를 쓸 수 없어도(Windows GUI 등) 앱 동작에는 영향을 주지 않음.
96 // eprint!는 시험 실행 중에는 시험별로 출력을 모아 실패한 시험만 보여 줌.
97 if std::panic::catch_unwind(|| eprint!("{line}")).is_err() {
98 // 표준 오류가 닫혀 있어 eprint!가 실패해도 무시함.
99 }
100}
101
102#[macro_export]
103macro_rules! log_at {
104 ($level:expr, $($arg:tt)+) => {
105 if $crate::applog::enabled($level) {
106 $crate::applog::write($level, module_path!(), format_args!($($arg)+));
107 }
108 };
109}
110
111#[macro_export]
112macro_rules! log_error { ($($arg:tt)+) => { $crate::log_at!($crate::applog::Level::Error, $($arg)+) }; }
113#[macro_export]
114macro_rules! log_warn { ($($arg:tt)+) => { $crate::log_at!($crate::applog::Level::Warn, $($arg)+) }; }
115#[macro_export]
116macro_rules! log_info { ($($arg:tt)+) => { $crate::log_at!($crate::applog::Level::Info, $($arg)+) }; }
117#[macro_export]
118macro_rules! log_debug { ($($arg:tt)+) => { $crate::log_at!($crate::applog::Level::Debug, $($arg)+) }; }
119#[macro_export]
120macro_rules! log_trace { ($($arg:tt)+) => { $crate::log_at!($crate::applog::Level::Trace, $($arg)+) }; }
121
122/// Debug 표현을 최대 `max`자까지만 만들어 돌려줌. 큰 값(미리보기 데이터 등)을
123/// 끝까지 문자열로 만들지 않도록 한도에 닿으면 바로 멈춤.
124pub fn brief(value: &impl std::fmt::Debug, max: usize) -> String {
125 struct Bounded {
126 text: String,
127 count: usize,
128 max: usize,
129 cut: bool,
130 }
131 impl std::fmt::Write for Bounded {
132 fn write_str(&mut self, s: &str) -> std::fmt::Result {
133 for c in s.chars() {
134 if self.count >= self.max {
135 self.cut = true;
136 return Err(std::fmt::Error);
137 }
138 self.text.push(c);
139 self.count += 1;
140 }
141 Ok(())
142 }
143 }
144 let mut out = Bounded {
145 text: String::new(),
146 count: 0,
147 max,
148 cut: false,
149 };
150 let _ = std::fmt::Write::write_fmt(&mut out, format_args!("{value:?}"));
151 if out.cut {
152 out.text.push('…');
153 }
154 out.text
155}
156
157#[cfg(test)]
158#[path = "../../../tests/rust-app-ui/applog.rs"]
159mod tests;