-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogging.rs
More file actions
74 lines (61 loc) · 2.74 KB
/
logging.rs
File metadata and controls
74 lines (61 loc) · 2.74 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
//! Global unlost logging with daily rotation.
//!
//! Logs are stored in the unlost data directory (`~/.unlost/logs/`) as daily rotating files.
//! All unlost instances share the same log files, making debugging easier.
use tracing_appender::rolling::{RollingFileAppender, Rotation};
/// A guard that must be kept alive for the duration of the program to ensure
/// logs are flushed. When dropped, the non-blocking writer will flush remaining logs.
pub struct LogGuard {
_guard: tracing_appender::non_blocking::WorkerGuard,
}
/// Initialize logging to both stderr and a file in the unlost data directory.
/// Returns a guard that must be kept alive for the duration of logging.
///
/// Log files are created at `~/.unlost/logs/unlost.YYYY-MM-DD.log`.
pub fn init_logging(filter: tracing_subscriber::EnvFilter) -> LogGuard {
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
let log_dir = crate::unlost_data_root().join("logs");
std::fs::create_dir_all(&log_dir).ok();
let file_appender = RollingFileAppender::new(Rotation::DAILY, &log_dir, "unlost.log");
let (non_blocking, guard) = tracing_appender::non_blocking(file_appender);
tracing_subscriber::registry()
.with(filter)
.with(
tracing_subscriber::fmt::layer()
.with_writer(std::io::stderr)
.with_ansi(true),
)
.with(
tracing_subscriber::fmt::layer()
.with_writer(non_blocking)
.with_ansi(false),
)
.init();
LogGuard { _guard: guard }
}
/// Initialize logging to file only (no stderr).
/// Useful for shims/companions where stdout/stderr are used for protocol communication.
pub fn init_logging_file_only(filter: tracing_subscriber::EnvFilter) -> LogGuard {
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
let log_dir = crate::unlost_data_root().join("logs");
std::fs::create_dir_all(&log_dir).ok();
let file_appender = RollingFileAppender::new(Rotation::DAILY, &log_dir, "unlost.log");
let (non_blocking, guard) = tracing_appender::non_blocking(file_appender);
tracing_subscriber::registry()
.with(filter)
.with(
tracing_subscriber::fmt::layer()
.with_writer(non_blocking)
.with_ansi(false),
)
.init();
LogGuard { _guard: guard }
}
/// Create a filter for unlost logs at the given level, keeping dependencies quiet.
pub fn create_filter(level: &str) -> tracing_subscriber::EnvFilter {
tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| {
tracing_subscriber::EnvFilter::new(format!("unlost={},lance=warn,lancedb=warn", level))
})
}