Skip to main content

bee_tui/
logging.rs

1use tracing_error::ErrorLayer;
2use tracing_subscriber::{EnvFilter, fmt, prelude::*};
3
4use crate::config;
5use crate::log_capture;
6
7lazy_static::lazy_static! {
8    pub static ref LOG_ENV: String = format!("{}_LOG_LEVEL", config::PROJECT_NAME.clone());
9    pub static ref LOG_FILE: String = format!("{}.log", env!("CARGO_PKG_NAME"));
10}
11
12pub fn init() -> color_eyre::Result<()> {
13    let directory = config::get_data_dir();
14    std::fs::create_dir_all(directory.clone())?;
15    let log_path = directory.join(LOG_FILE.clone());
16    let log_file = std::fs::File::create(log_path)?;
17    let env_filter = EnvFilter::builder().with_default_directive(tracing::Level::INFO.into());
18    // If the `RUST_LOG` environment variable is set, use that as the default, otherwise use the
19    // value of the `LOG_ENV` environment variable. If the `LOG_ENV` environment variable contains
20    // errors, then this will return an error.
21    let env_filter = env_filter
22        .try_from_env()
23        .or_else(|_| env_filter.with_env_var(LOG_ENV.clone()).from_env())?;
24    let file_subscriber = fmt::layer()
25        .with_file(true)
26        .with_line_number(true)
27        .with_writer(log_file)
28        .with_target(false)
29        .with_ansi(false)
30        .with_filter(env_filter);
31    // S10 Command-log capture: stash bee::http events in a process-
32    // wide ring buffer so the cockpit's command-log pane can render
33    // them. Capacity 200 lines = a few minutes of activity at the
34    // typical poll rate.
35    let capture = log_capture::install(200);
36    let capture_layer = log_capture::CaptureLayer::new(capture);
37
38    tracing_subscriber::registry()
39        .with(file_subscriber)
40        .with(capture_layer)
41        .with(ErrorLayer::default())
42        .try_init()?;
43    Ok(())
44}