-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogging.rs
More file actions
83 lines (71 loc) · 2.3 KB
/
logging.rs
File metadata and controls
83 lines (71 loc) · 2.3 KB
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
use std::backtrace::Backtrace;
use std::fs::{self, OpenOptions};
use std::path::PathBuf;
use anyhow::Result;
use tracing::{error, info};
use tracing_appender::non_blocking::WorkerGuard;
use tracing_subscriber::{EnvFilter, fmt, layer::SubscriberExt, util::SubscriberInitExt};
pub struct LoggingGuard {
_guard: WorkerGuard,
pub log_path: PathBuf,
}
pub fn init() -> Result<LoggingGuard> {
let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let log_dir = root.join("logs");
fs::create_dir_all(&log_dir)?;
let log_path = log_dir.join("riggy.log");
let log_file = OpenOptions::new()
.create(true)
.append(true)
.open(&log_path)?;
let (writer, guard) = tracing_appender::non_blocking(log_file);
let env_filter = EnvFilter::try_from_default_env()
.unwrap_or_else(|_| EnvFilter::new("riggy=trace,rig=debug,info"));
tracing_subscriber::registry()
.with(env_filter)
.with(
fmt::layer()
.compact()
.with_ansi(false)
.with_writer(writer)
.with_target(true)
.with_thread_names(true)
)
.try_init()?;
install_panic_hook();
info!(log_path = %log_path.display(), "logging initialized");
Ok(LoggingGuard {
_guard: guard,
log_path,
})
}
fn install_panic_hook() {
let default_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |panic_info| {
let location = panic_info
.location()
.map(|location| {
format!(
"{}:{}:{}",
location.file(),
location.line(),
location.column()
)
})
.unwrap_or_else(|| "<unknown>".to_string());
let payload = if let Some(message) = panic_info.payload().downcast_ref::<&str>() {
(*message).to_string()
} else if let Some(message) = panic_info.payload().downcast_ref::<String>() {
message.clone()
} else {
"non-string panic payload".to_string()
};
error!(
%location,
%payload,
backtrace = %Backtrace::force_capture(),
"application panicked"
);
default_hook(panic_info);
}));
}