Skip to main content

cosmic_applet_avestruz/
logging.rs

1// SPDX-License-Identifier: MIT
2
3//! Runtime-adjustable log level.
4//!
5//! Avestruz logs to one place: stderr, which cosmic-panel forwards to the
6//! systemd journal, and which is the terminal when the applet is run from
7//! one.
8//!
9//! `main` builds the tracing subscriber with its filter wrapped in a
10//! [`tracing_subscriber::reload`] layer, then installs a reload hook here
11//! with [`install_reload_hook`]. The settings view calls
12//! [`set_console_level`] to change how much is logged **live**, without a
13//! restart: an applet has no command line to set `RUST_LOG` on.
14
15use std::sync::OnceLock;
16
17use crate::config::LogLevel;
18
19/// Rebuilds the filter for a level and swaps it into the live subscriber.
20/// Installed once by `main`.
21type ReloadHook = Box<dyn Fn(LogLevel) + Send + Sync>;
22
23static RELOAD: OnceLock<ReloadHook> = OnceLock::new();
24
25/// Register the reload hook. Called once from `main` after the tracing
26/// subscriber is initialized. Later calls are ignored.
27pub fn install_reload_hook(hook: ReloadHook) {
28    let _ = RELOAD.set(hook);
29}
30
31/// Apply a new log level at runtime.
32///
33/// Does nothing if the hook hasn't been installed (in tests, which never
34/// initialize tracing), so callers don't need to special-case that.
35pub fn set_console_level(level: LogLevel) {
36    if let Some(hook) = RELOAD.get() {
37        hook(level);
38    }
39}
40
41/// Whether `RUST_LOG` says how much to log. If it does, it is what `main`
42/// went by, and it keeps precedence over the setting.
43pub fn level_set_by_environment() -> bool {
44    std::env::var_os("RUST_LOG").is_some()
45}