flexi_logger/
filter.rs

1//! This module contains two traits which allow adding a stateful filter
2//! using [`Logger::filter`](crate::Logger::filter).
3//!
4//! # Example
5//!
6//! ```rust
7//! use flexi_logger::{
8//!     filter::{LogLineFilter, LogLineWriter},
9//!     DeferredNow, FlexiLoggerError,
10//! };
11//!
12//! pub struct BarsOnly;
13//! impl LogLineFilter for BarsOnly {
14//!     fn write(
15//!         &self,
16//!         now: &mut DeferredNow,
17//!         record: &log::Record,
18//!         log_line_writer: &dyn LogLineWriter,
19//!     ) -> std::io::Result<()> {
20//!         if record.args().to_string().contains("bar") {
21//!             log_line_writer.write(now, record)?;
22//!         }
23//!         Ok(())
24//!     }
25//! }
26//!
27//! fn main() -> Result<(), FlexiLoggerError> {
28//!     flexi_logger::Logger::try_with_str("info")?
29//!         .filter(Box::new(BarsOnly))
30//!         .start()?;
31//!     log::info!("barista");
32//!     log::info!("foo"); // will be swallowed by the filter
33//!     log::info!("bar");
34//!     log::info!("gaga"); // will be swallowed by the filter
35//!     Ok(())
36//! }
37//! ```
38use crate::DeferredNow;
39use log::Record;
40
41/// Trait of the filter object.
42#[allow(clippy::module_name_repetitions)]
43pub trait LogLineFilter {
44    /// Each log line that `flexi_logger` would write to the configured output channel is
45    /// sent to this method.
46    ///
47    /// Note that the log line only appears in the configured output channel if the
48    /// filter implementation forwards it to the provided `LogLineWriter`.
49    ///
50    /// # Errors
51    ///
52    /// If writing to the configured output channel fails.
53    fn write(
54        &self,
55        now: &mut DeferredNow,
56        record: &Record,
57        log_line_writer: &dyn LogLineWriter,
58    ) -> std::io::Result<()>;
59}
60
61/// Write out a single log line
62pub trait LogLineWriter {
63    /// Write out a log line to the configured output channel.
64    ///
65    /// # Errors
66    ///
67    /// If writing to the configured output channel fails.
68    fn write(&self, now: &mut DeferredNow, record: &Record) -> std::io::Result<()>;
69}