| 354 | } |
| 355 | |
| 356 | pub fn init_tracing(_level: Option<&str>, log_dir: Option<PathBuf>, print: bool) -> Option<PathBuf> { |
| 357 | if print { |
| 358 | let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")); |
| 359 | tracing_subscriber::registry() |
| 360 | .with(filter) |
| 361 | .with(fmt::layer()) |
| 362 | .init(); |
| 363 | return None; |
| 364 | } |
| 365 | |
| 366 | let log_dir = log_dir.unwrap_or_else(|| PathBuf::from(".")); |
| 367 | let timestamp = Local::now().format("%Y-%m-%dT%H%M%S").to_string(); |
| 368 | let log_path = log_dir.join(format!("{}.log", timestamp)); |
| 369 | |
| 370 | if let Some(parent) = log_path.parent() { |
| 371 | let _ = std::fs::create_dir_all(parent); |
| 372 | } |
| 373 | |
| 374 | let file = std::fs::OpenOptions::new() |
| 375 | .create(true) |
| 376 | .write(true) |
| 377 | .truncate(true) |
| 378 | .open(&log_path) |
| 379 | .ok(); |
| 380 | |
| 381 | if let Some(file) = file { |
| 382 | let (non_blocking, _guard) = tracing_appender::non_blocking(file); |
| 383 | let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")); |
| 384 | tracing_subscriber::registry() |
| 385 | .with(filter) |
| 386 | .with(fmt::layer().with_writer(non_blocking)) |
| 387 | .init(); |
| 388 | } |
| 389 | |
| 390 | Some(log_path) |
| 391 | } |