Skip to main content

ash_log/
filter.rs

1//! Level thresholds that vary by module, adjustable at runtime.
2//!
3//! # Why this exists
4//!
5//! A single global threshold forces a choice between drowning in one noisy
6//! module's diagnostics and losing visibility everywhere else. Raising the
7//! level to silence one component silences the rest with it.
8//!
9//! [`FilterDirectives`] applies a different threshold per module path, in the
10//! shape most Rust developers already know from `RUST_LOG`:
11//!
12//! ```text
13//! info,my_app::db=debug,hyper=warn
14//! ```
15//!
16//! # This filters diagnostics only
17//!
18//! Security events are admitted whatever any threshold says. A filter tunes
19//! operational noise; it cannot shrink the audit record, and a directive
20//! naming a module that only emits security events has no effect.
21
22use super::AuditSeverity;
23use std::sync::{Arc, RwLock};
24
25/// One `module=level` rule.
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct Directive {
28    /// Module prefix this applies to. Empty means the default for everything.
29    pub target: String,
30    /// Minimum severity admitted for that prefix.
31    pub level: AuditSeverity,
32}
33
34/// A parsed set of per-module thresholds.
35///
36/// # Examples
37///
38/// ```rust
39/// use ash_log::*;
40///
41/// let filter = FilterDirectives::parse("info,my_app::db=trace,hyper=warn");
42///
43/// assert_eq!(filter.level_for("my_app::db::pool"), AuditSeverity::Trace);
44/// assert_eq!(filter.level_for("hyper::client"), AuditSeverity::Warning);
45/// assert_eq!(filter.level_for("anything_else"), AuditSeverity::Info);
46/// ```
47#[derive(Debug, Clone, Default)]
48pub struct FilterDirectives {
49    default: Option<AuditSeverity>,
50    directives: Vec<Directive>,
51}
52
53impl FilterDirectives {
54    /// Parse a `RUST_LOG`-style directive string.
55    ///
56    /// Comma-separated entries, each either a bare level (the default for
57    /// every module) or `target=level`. Unparseable entries are skipped rather
58    /// than failing the whole string: a typo in one directive must not silence
59    /// the logger entirely.
60    #[must_use]
61    pub fn parse(directives: &str) -> Self {
62        let mut default = None;
63        let mut parsed = Vec::new();
64
65        for entry in directives.split(',') {
66            let entry = entry.trim();
67            if entry.is_empty() {
68                continue;
69            }
70
71            match entry.split_once('=') {
72                None => {
73                    if let Ok(level) = entry.parse::<AuditSeverity>() {
74                        default = Some(level);
75                    }
76                }
77                Some((target, level)) => {
78                    if let Ok(level) = level.trim().parse::<AuditSeverity>() {
79                        parsed.push(Directive {
80                            target: target.trim().to_string(),
81                            level,
82                        });
83                    }
84                }
85            }
86        }
87
88        // Longest target first, so the most specific rule wins regardless of
89        // the order they were written in.
90        parsed.sort_by_key(|d| std::cmp::Reverse(d.target.len()));
91
92        Self {
93            default,
94            directives: parsed,
95        }
96    }
97
98    /// Read directives from an environment variable.
99    ///
100    /// Returns an empty filter if the variable is unset, which admits
101    /// everything the logger's own threshold admits.
102    #[must_use]
103    pub fn from_env(var: &str) -> Self {
104        std::env::var(var).map_or_else(|_| Self::default(), |value| Self::parse(&value))
105    }
106
107    /// The threshold for `module`, falling back to `Trace` when nothing matches
108    /// and no default was given — the filter then defers entirely to the
109    /// logger's own level.
110    #[must_use]
111    pub fn level_for(&self, module: &str) -> AuditSeverity {
112        self.directives
113            .iter()
114            .find(|d| module == d.target || module.starts_with(&format!("{}::", d.target)))
115            .map_or_else(|| self.default.unwrap_or(AuditSeverity::Trace), |d| d.level)
116    }
117
118    /// Whether a default level was specified.
119    #[must_use]
120    pub fn has_default(&self) -> bool {
121        self.default.is_some()
122    }
123
124    /// The parsed directives, most specific first.
125    #[must_use]
126    pub fn directives(&self) -> &[Directive] {
127        &self.directives
128    }
129
130    /// Whether this filter says anything at all.
131    #[must_use]
132    pub fn is_empty(&self) -> bool {
133        self.default.is_none() && self.directives.is_empty()
134    }
135}
136
137/// A filter that can be replaced while the logger is running.
138///
139/// Cloning shares the same underlying filter, so a handle kept by an admin
140/// endpoint retunes every logger built from it.
141///
142/// # Examples
143///
144/// ```rust
145/// use ash_log::*;
146/// use std::sync::Arc;
147///
148/// let filter = LiveFilter::new(FilterDirectives::parse("info"));
149/// let logger = ash_logger!(
150///     backend: Arc::new(NoopAuditBackend),
151///     filter: filter.clone(),
152///     min_level: AuditSeverity::Trace,
153/// );
154///
155/// ash_debug!(logger, "not recorded at info");
156///
157/// // Retune without rebuilding the logger.
158/// filter.set(FilterDirectives::parse("debug"));
159/// ash_debug!(logger, "recorded now");
160/// ```
161#[derive(Debug, Clone, Default)]
162pub struct LiveFilter {
163    inner: Arc<RwLock<FilterDirectives>>,
164}
165
166impl LiveFilter {
167    /// Wrap `directives` in a handle that can be updated later.
168    #[must_use]
169    pub fn new(directives: FilterDirectives) -> Self {
170        Self {
171            inner: Arc::new(RwLock::new(directives)),
172        }
173    }
174
175    /// Parse and wrap a directive string.
176    #[must_use]
177    pub fn parse(directives: &str) -> Self {
178        Self::new(FilterDirectives::parse(directives))
179    }
180
181    /// Read directives from an environment variable.
182    #[must_use]
183    pub fn from_env(var: &str) -> Self {
184        Self::new(FilterDirectives::from_env(var))
185    }
186
187    /// Replace the directives. Takes effect on the next event.
188    pub fn set(&self, directives: FilterDirectives) {
189        *self
190            .inner
191            .write()
192            .unwrap_or_else(std::sync::PoisonError::into_inner) = directives;
193    }
194
195    /// Replace the directives by parsing a new string.
196    pub fn reload(&self, directives: &str) {
197        self.set(FilterDirectives::parse(directives));
198    }
199
200    /// The threshold currently applying to `module`.
201    #[must_use]
202    pub fn level_for(&self, module: &str) -> AuditSeverity {
203        self.read().level_for(module)
204    }
205
206    /// Whether the filter is empty, meaning it constrains nothing.
207    #[must_use]
208    pub fn is_empty(&self) -> bool {
209        self.read().is_empty()
210    }
211
212    /// A snapshot of the current directives.
213    #[must_use]
214    pub fn snapshot(&self) -> FilterDirectives {
215        self.read().clone()
216    }
217
218    /// Read the filter, recovering from a poisoned lock.
219    ///
220    /// A panic while holding the lock must not stop logging: the directives are
221    /// still valid data, and refusing to log would be the worse outcome.
222    fn read(&self) -> std::sync::RwLockReadGuard<'_, FilterDirectives> {
223        self.inner
224            .read()
225            .unwrap_or_else(std::sync::PoisonError::into_inner)
226    }
227}
228
229#[cfg(test)]
230mod tests {
231    use super::*;
232
233    #[test]
234    fn test_a_bare_level_sets_the_default() {
235        let filter = FilterDirectives::parse("warn");
236        assert_eq!(filter.level_for("anything"), AuditSeverity::Warning);
237        assert!(filter.has_default());
238    }
239
240    #[test]
241    fn test_per_module_directives_override_the_default() {
242        let filter = FilterDirectives::parse("info,my_app::db=trace,hyper=warn");
243
244        assert_eq!(filter.level_for("my_app::db"), AuditSeverity::Trace);
245        assert_eq!(filter.level_for("my_app::db::pool"), AuditSeverity::Trace);
246        assert_eq!(filter.level_for("hyper::client"), AuditSeverity::Warning);
247        assert_eq!(filter.level_for("my_app::api"), AuditSeverity::Info);
248    }
249
250    #[test]
251    fn test_the_most_specific_directive_wins_regardless_of_order() {
252        // Written least-specific first, so ordering must come from the match
253        // logic rather than from how the string happened to be typed.
254        let filter = FilterDirectives::parse("my_app=warn,my_app::db=trace");
255
256        assert_eq!(filter.level_for("my_app::db::pool"), AuditSeverity::Trace);
257        assert_eq!(filter.level_for("my_app::api"), AuditSeverity::Warning);
258    }
259
260    #[test]
261    fn test_prefix_matching_respects_module_boundaries() {
262        // `my_app` must not match `my_application`, or an unrelated crate would
263        // silently inherit another's threshold.
264        let filter = FilterDirectives::parse("error,my_app=trace");
265
266        assert_eq!(filter.level_for("my_app::db"), AuditSeverity::Trace);
267        assert_eq!(
268            filter.level_for("my_application::db"),
269            AuditSeverity::Error,
270            "a longer name that merely starts with the target does not match"
271        );
272    }
273
274    #[test]
275    fn test_a_malformed_directive_is_skipped_not_fatal() {
276        // A typo must not silence the logger, so bad entries are dropped and
277        // the good ones still apply.
278        let filter = FilterDirectives::parse("info,my_app::db=nonsense,hyper=warn");
279
280        assert_eq!(filter.level_for("hyper"), AuditSeverity::Warning);
281        assert_eq!(
282            filter.level_for("my_app::db"),
283            AuditSeverity::Info,
284            "the unparseable directive falls back to the default"
285        );
286    }
287
288    #[test]
289    fn test_an_empty_filter_constrains_nothing() {
290        let filter = FilterDirectives::parse("");
291        assert!(filter.is_empty());
292        assert_eq!(
293            filter.level_for("anything"),
294            AuditSeverity::Trace,
295            "with nothing specified the logger's own threshold decides"
296        );
297    }
298
299    #[test]
300    fn test_levels_accept_the_usual_aliases() {
301        let filter = FilterDirectives::parse("a=warn,b=warning,c=crit");
302        assert_eq!(filter.level_for("a"), AuditSeverity::Warning);
303        assert_eq!(filter.level_for("b"), AuditSeverity::Warning);
304        assert_eq!(filter.level_for("c"), AuditSeverity::Critical);
305    }
306
307    #[test]
308    fn test_live_filter_updates_are_visible_immediately() {
309        let filter = LiveFilter::parse("info");
310        assert_eq!(filter.level_for("app"), AuditSeverity::Info);
311
312        filter.reload("app=trace,warn");
313        assert_eq!(filter.level_for("app"), AuditSeverity::Trace);
314        assert_eq!(filter.level_for("other"), AuditSeverity::Warning);
315    }
316
317    #[test]
318    fn test_clones_share_one_filter() {
319        // An admin endpoint holding a clone must be able to retune loggers
320        // built from the original.
321        let filter = LiveFilter::parse("info");
322        let handle = filter.clone();
323
324        handle.reload("trace");
325        assert_eq!(
326            filter.level_for("app"),
327            AuditSeverity::Trace,
328            "the update is visible through the original handle"
329        );
330    }
331
332    #[test]
333    fn test_whitespace_is_tolerated() {
334        let filter = FilterDirectives::parse(" info , my_app::db = debug ");
335        assert_eq!(filter.level_for("my_app::db"), AuditSeverity::Debug);
336        assert_eq!(filter.level_for("other"), AuditSeverity::Info);
337    }
338}