File size: 9,896 Bytes
bc32e7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
//! 日志系统初始化与控制台恢复。

use std::fs::{self, File};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use std::{io, panic, thread, time::Duration};

use crossterm::event::DisableMouseCapture;
use crossterm::execute;
use crossterm::terminal::{LeaveAlternateScreen, disable_raw_mode};
use ctrlc;
use time::OffsetDateTime;
use time::macros::format_description;
use tracing::{error, info};
use tracing_appender::non_blocking::{self, WorkerGuard};
use tracing_appender::rolling;
use tracing_subscriber::Layer;
use tracing_subscriber::filter::LevelFilter;
use tracing_subscriber::fmt;
use tracing_subscriber::fmt::MakeWriter;
use tracing_subscriber::fmt::writer::BoxMakeWriter;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use zip::CompressionMethod;
use zip::write::FileOptions;

const MAX_LOG_BYTES: u64 = 10 * 1024 * 1024; // 10MB
const ARCHIVE_WAIT_MS: u64 = 1000; // allow file handles to settle on Windows

#[derive(Debug, thiserror::Error)]
pub enum LogError {
    #[error("logging already initialized")]
    AlreadyInitialized,
    #[error("subscriber init failed: {0}")]
    SubscriberInit(#[from] tracing_subscriber::util::TryInitError),
    #[error("io error: {0}")]
    Io(#[from] io::Error),
    #[error("zip error: {0}")]
    Zip(#[from] zip::result::ZipError),
    #[error("time formatting failed: {0}")]
    Time(#[from] time::error::Format),
}

#[derive(Clone, Copy, Debug)]
pub struct LogOptions {
    pub debug: bool,
    pub use_color: bool,
    pub archive_on_exit: bool,
    pub console: bool,
    pub broadcast_to_ui: bool,
}

impl Default for LogOptions {
    fn default() -> Self {
        Self {
            debug: false,
            use_color: true,
            archive_on_exit: true,
            console: true,
            broadcast_to_ui: true,
        }
    }
}

static LOG_CHANNEL: OnceLock<(
    crossbeam_channel::Sender<String>,
    crossbeam_channel::Receiver<String>,
)> = OnceLock::new();
static LOGS_DIR: OnceLock<PathBuf> = OnceLock::new();

pub fn current_logs_dir() -> Option<PathBuf> {
    LOGS_DIR.get().cloned()
}

#[derive(Clone)]
struct ChannelWriter {
    tx: crossbeam_channel::Sender<String>,
}

impl std::io::Write for ChannelWriter {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        let text = String::from_utf8_lossy(buf).to_string();
        let _ = self.tx.send(text);
        Ok(buf.len())
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

pub fn take_broadcast_rx() -> Option<crossbeam_channel::Receiver<String>> {
    LOG_CHANNEL.get().map(|(_, rx)| rx.clone())
}

#[derive(Clone)]
struct ChannelWriterMake {
    tx: crossbeam_channel::Sender<String>,
}

impl<'a> MakeWriter<'a> for ChannelWriterMake {
    type Writer = ChannelWriter;

    fn make_writer(&'a self) -> Self::Writer {
        ChannelWriter {
            tx: self.tx.clone(),
        }
    }
}

pub struct LogSystem {
    runtime: Arc<LogRuntime>,
}

impl LogSystem {
    pub fn init(options: LogOptions) -> Result<Self, LogError> {
        Self::init_with_base(options, None)
    }

    /// Initialize the logging system, optionally using a base directory.
    ///
    /// # Arguments
    /// * `options` - Logging configuration options
    /// * `base_dir` - If provided, creates logs in base_dir/logs, otherwise uses ./logs
    pub fn init_with_base(options: LogOptions, base_dir: Option<&Path>) -> Result<Self, LogError> {
        let logs_dir = if let Some(base) = base_dir {
            base.join("logs")
        } else {
            PathBuf::from("logs")
        };
        fs::create_dir_all(&logs_dir)?;
        let _ = LOGS_DIR.set(logs_dir.clone());
        let latest_log = logs_dir.join("latest.log");

        archive_if_large(&latest_log, &logs_dir)?;

        let file_appender = rolling::never(&logs_dir, "latest.log");
        let (file_writer, guard) = non_blocking::NonBlockingBuilder::default()
            .lossy(false)
            .finish(file_appender);

        let console_level = if options.debug {
            LevelFilter::DEBUG
        } else {
            LevelFilter::INFO
        };

        let console_writer: BoxMakeWriter = if options.console {
            BoxMakeWriter::new(io::stdout)
        } else {
            BoxMakeWriter::new(io::sink)
        };

        let console_layer = fmt::layer()
            .with_target(false)
            .with_level(true)
            .with_thread_names(true)
            .with_ansi(options.use_color)
            .with_writer(console_writer)
            .with_filter(console_level);

        let broadcast_layer = if options.broadcast_to_ui {
            let (tx, _rx) = LOG_CHANNEL
                .get_or_init(crossbeam_channel::unbounded)
                .clone();
            let writer = BoxMakeWriter::new(ChannelWriterMake { tx });
            Some(
                fmt::layer()
                    .with_target(false)
                    .with_level(true)
                    .with_thread_names(false)
                    .with_ansi(false)
                    .with_writer(writer)
                    .with_filter(console_level),
            )
        } else {
            None
        };

        let file_level = if options.debug {
            LevelFilter::DEBUG
        } else {
            LevelFilter::INFO
        };

        let file_layer = fmt::layer()
            .with_target(false)
            .with_level(true)
            .with_thread_names(true)
            .with_ansi(false)
            .with_writer(file_writer)
            .with_filter(file_level);

        tracing_subscriber::registry()
            .with(console_layer)
            .with(file_layer)
            .with(broadcast_layer)
            .try_init()
            .map_err(|e| {
                let msg = e.to_string();
                if msg.contains("global subscriber") || msg.contains("already") {
                    LogError::AlreadyInitialized
                } else {
                    LogError::SubscriberInit(e)
                }
            })?;

        let runtime = Arc::new(LogRuntime {
            logs_dir,
            latest_log,
            guard: Mutex::new(Some(guard)),
            exit_hooks: Mutex::new(Vec::new()),
            exit_called: AtomicBool::new(false),
            archive_on_exit: options.archive_on_exit,
        });

        runtime.install_signal_handler();
        runtime.install_panic_hook();

        Ok(Self { runtime })
    }
}

impl Drop for LogSystem {
    fn drop(&mut self) {
        self.runtime.safe_exit();
    }
}

struct LogRuntime {
    logs_dir: PathBuf,
    latest_log: PathBuf,
    guard: Mutex<Option<WorkerGuard>>,
    exit_hooks: Mutex<Vec<Box<dyn FnOnce() + Send + 'static>>>,
    exit_called: AtomicBool,
    archive_on_exit: bool,
}

impl LogRuntime {
    fn install_signal_handler(self: &Arc<Self>) {
        let runtime = Arc::clone(self);
        let _ = ctrlc::set_handler(move || {
            // Best-effort console restore: if the app is in TUI raw mode / alt screen,
            // leaving it as-is will make subsequent PowerShell input appear "stuck".
            let _ = disable_raw_mode();
            let mut out = io::stdout();
            let _ = execute!(out, DisableMouseCapture, LeaveAlternateScreen);

            runtime.safe_exit();
            std::process::exit(0);
        });
    }

    fn install_panic_hook(self: &Arc<Self>) {
        let runtime = Arc::clone(self);
        let previous = panic::take_hook();
        panic::set_hook(Box::new(move |info| {
            if let Some(location) = info.location() {
                error!("panic at {}:{}: {}", location.file(), location.line(), info);
            } else {
                error!("panic: {info}");
            }
            runtime.safe_exit();
            previous(info);
        }));
    }

    fn safe_exit(&self) {
        if self.exit_called.swap(true, Ordering::SeqCst) {
            return;
        }

        if let Ok(mut hooks) = self.exit_hooks.lock() {
            while let Some(func) = hooks.pop() {
                func();
            }
        }

        if let Ok(mut guard) = self.guard.lock() {
            guard.take();
        }

        thread::sleep(Duration::from_millis(ARCHIVE_WAIT_MS));

        if self.archive_on_exit
            && let Err(err) = archive_log_file(&self.latest_log, &self.logs_dir)
        {
            eprintln!("failed to archive log: {err}");
        }
    }
}

fn archive_if_large(latest_log: &Path, logs_dir: &Path) -> Result<(), LogError> {
    if let Ok(meta) = fs::metadata(latest_log)
        && meta.len() >= MAX_LOG_BYTES
    {
        archive_log_file(latest_log, logs_dir)?;
    }
    Ok(())
}

fn archive_log_file(latest_log: &Path, logs_dir: &Path) -> Result<Option<PathBuf>, LogError> {
    if !latest_log.exists() {
        return Ok(None);
    }
    let meta = fs::metadata(latest_log)?;
    if meta.len() == 0 {
        let _ = fs::remove_file(latest_log);
        return Ok(None);
    }

    let timestamp = OffsetDateTime::now_utc().format(format_description!(
        "[year][month][day]_[hour][minute][second]"
    ))?;
    let archive_path = logs_dir.join(format!("log_{timestamp}.zip"));
    let temp_log = logs_dir.join(format!("temp_{timestamp}.log"));
    fs::copy(latest_log, &temp_log)?;

    let file = File::create(&archive_path)?;
    let mut zip = zip::ZipWriter::new(file);
    let options = FileOptions::default().compression_method(CompressionMethod::Deflated);
    zip.start_file(format!("{timestamp}.log"), options)?;

    let mut temp_file = File::open(&temp_log)?;
    io::copy(&mut temp_file, &mut zip)?;
    zip.finish()?;

    let _ = fs::remove_file(&temp_log);
    let _ = fs::remove_file(latest_log);

    info!("log archived to {}", archive_path.display());
    Ok(Some(archive_path))
}