Something went wrong. Try again.
A terminal UI for Libby libbui.vinnymac.dev
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122//! File-only `tracing` setup.//!//! The TUI owns the terminal, so logs never go to stdout or stderr: they go//! to `libbui.<date>.log` in [`Paths::log_dir`], rotated daily, keeping the//! last [`KEEP_FILES`] files. Writing happens on a background thread; keep//! the returned [`LogGuard`] alive for the life of the program so buffered//! lines are flushed on exit.
use tracing_appender::non_blocking::WorkerGuard;use tracing_appender::rolling::{RollingFileAppender, Rotation};use tracing_subscriber::EnvFilter;use tracing_subscriber::layer::SubscriberExt;use tracing_subscriber::util::SubscriberInitExt;
use crate::paths::Paths;
/// How many daily log files are kept.pub const KEEP_FILES: usize = 7;
/// Flushes buffered log lines when dropped.#[derive(Debug)]#[must_use = "logs stop being written when the guard is dropped"]pub struct LogGuard { _worker: WorkerGuard,}
/// Why logging could not be set up.#[derive(Debug, thiserror::Error)]pub enum LoggingError { /// The log directory could not be created. #[error("cannot create log directory {}: {source}", path.display())] Dir { /// The log directory. path: std::path::PathBuf, /// The underlying error. #[source] source: std::io::Error, }, /// The rolling file appender could not be created. #[error("cannot open log file: {0}")] Appender(#[from] tracing_appender::rolling::InitError), /// `level` is not a valid filter directive. #[error("invalid log level {level:?}: {source}")] Filter { /// What was passed. level: String, /// The parser's description. #[source] source: tracing_subscriber::filter::ParseError, }, /// A global subscriber is already installed. #[error("logging is already initialized: {0}")] AlreadySet(#[from] tracing_subscriber::util::TryInitError),}
/// Builds the rotating file appender for `paths.log_dir`.fn appender(paths: &Paths) -> Result<RollingFileAppender, LoggingError> { std::fs::create_dir_all(&paths.log_dir).map_err(|source| LoggingError::Dir { path: paths.log_dir.clone(), source, })?; Ok(RollingFileAppender::builder() .rotation(Rotation::DAILY) .filename_prefix("libbui") .filename_suffix("log") .max_log_files(KEEP_FILES) .build(&paths.log_dir)?)}
/// Installs the global `tracing` subscriber writing to the log directory.////// `level` is an [`EnvFilter`] directive such as `"info"` or/// `"libbui=debug,reqwest=warn"`.////// # Errors/// See [`LoggingError`]. Calling this twice is an error.pub fn init(paths: &Paths, level: &str) -> Result<LogGuard, LoggingError> { let filter = EnvFilter::try_new(level).map_err(|source| LoggingError::Filter { level: level.to_owned(), source, })?; let (writer, worker) = tracing_appender::non_blocking(appender(paths)?); tracing_subscriber::registry() .with(filter) .with( tracing_subscriber::fmt::layer() .with_writer(writer) .with_ansi(false), ) .try_init()?; Ok(LogGuard { _worker: worker })}
#[cfg(test)]mod tests { #![allow(clippy::unwrap_used)] use super::*; use std::io::Write;
#[test] fn appender_writes_into_log_dir() { let dir = tempfile::tempdir().unwrap(); let paths = Paths::rooted_at(dir.path()); let mut a = appender(&paths).unwrap(); a.write_all(b"hello\n").unwrap(); a.flush().unwrap(); let files: Vec<_> = std::fs::read_dir(&paths.log_dir) .unwrap() .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) .collect(); assert_eq!(files.len(), 1, "{files:?}"); assert!(files[0].starts_with("libbui.") && files[0].ends_with(".log")); }
#[test] fn bad_level_is_an_error() { let dir = tempfile::tempdir().unwrap(); let err = init(&Paths::rooted_at(dir.path()), "info,=[").unwrap_err(); assert!(matches!(err, LoggingError::Filter { .. }), "{err:?}"); }}