1 | use log::Log; |
2 | |
3 | use crate::Filter; |
4 | |
5 | /// Decorate a [`log::Log`] with record [`Filter`]ing. |
6 | /// |
7 | /// Records that match the filter will be forwarded to the wrapped log. |
8 | /// Other records will be ignored. |
9 | #[derive (Debug)] |
10 | pub struct FilteredLog<T> { |
11 | log: T, |
12 | filter: Filter, |
13 | } |
14 | |
15 | impl<T: Log> FilteredLog<T> { |
16 | /// Create a new filtered log. |
17 | pub fn new(log: T, filter: Filter) -> Self { |
18 | Self { log, filter } |
19 | } |
20 | } |
21 | |
22 | impl<T: Log> Log for FilteredLog<T> { |
23 | /// Determines if a log message with the specified metadata would be logged. |
24 | /// |
25 | /// For the wrapped log, this returns `true` only if both the filter and the wrapped log return `true`. |
26 | fn enabled(&self, metadata: &log::Metadata<'_>) -> bool { |
27 | self.filter.enabled(metadata) && self.log.enabled(metadata) |
28 | } |
29 | |
30 | /// Logs the record. |
31 | /// |
32 | /// Forwards the record to the wrapped log, but only if the record matches the filter. |
33 | fn log(&self, record: &log::Record<'_>) { |
34 | if self.filter.matches(record) { |
35 | self.log.log(record); |
36 | } |
37 | } |
38 | |
39 | /// Flushes any buffered records. |
40 | /// |
41 | /// Forwards directly to the wrapped log. |
42 | fn flush(&self) { |
43 | self.log.flush(); |
44 | } |
45 | } |
46 | |