| 1 |
use anyhow::Result; |
| 2 |
use crossterm::ExecutableCommand; |
| 3 |
use crossterm::terminal::{LeaveAlternateScreen, disable_raw_mode}; |
| 4 |
use log::LevelFilter; |
| 5 |
use simplelog::{CombinedLogger, Config, WriteLogger}; |
| 6 |
use std::fs::File; |
| 7 |
use std::io::stdout; |
| 8 |
use std::panic; |
| 9 |
use std::path::PathBuf; |
| 10 |
use std::{env, fs}; |
| 11 |
|
| 12 |
pub fn init() -> Result<()> { |
| 13 |
let level = match env::var("RUST_LOG") |
| 14 |
.unwrap_or_default() |
| 15 |
.to_lowercase() |
| 16 |
.as_str() |
| 17 |
{ |
| 18 |
"trace" => LevelFilter::Trace, |
| 19 |
"debug" => LevelFilter::Debug, |
| 20 |
"info" => LevelFilter::Info, |
| 21 |
"warn" => LevelFilter::Warn, |
| 22 |
"error" => LevelFilter::Error, |
| 23 |
_ => return Ok(()), |
| 24 |
}; |
| 25 |
let log_path = get_log_path(); |
| 26 |
let log_file = File::create(&log_path).expect("Failed to create log file."); |
| 27 |
|
| 28 |
CombinedLogger::init(vec![WriteLogger::new(level, Config::default(), log_file)]).unwrap(); |
| 29 |
|
| 30 |
let default_hook = panic::take_hook(); |
| 31 |
panic::set_hook(Box::new(move |panic_info| { |
| 32 |
error!("APPLICATION PANIC: {}", panic_info); |
| 33 |
|
| 34 |
let _ = disable_raw_mode_internal(); |
| 35 |
|
| 36 |
default_hook(panic_info); |
| 37 |
})); |
| 38 |
|
| 39 |
info!("Logger initialized successfully at {:?}", log_path); |
| 40 |
Ok(()) |
| 41 |
} |
| 42 |
|
| 43 |
pub fn get_log_path() -> PathBuf { |
| 44 |
let base = dirs::cache_dir().unwrap_or_else(|| PathBuf::from(".")); |
| 45 |
|
| 46 |
let dir = base.join("nmrs-tui"); |
| 47 |
fs::create_dir_all(&dir).expect("Failed to create log dir"); |
| 48 |
dir.join("nmrs-tui.log") |
| 49 |
} |
| 50 |
|
| 51 |
fn disable_raw_mode_internal() -> Result<()> { |
| 52 |
disable_raw_mode()?; |
| 53 |
stdout().execute(LeaveAlternateScreen)?; |
| 54 |
Ok(()) |
| 55 |
} |