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

/// Trait of the filter object.
#[allow(clippy::module_name_repetitions)]
pub trait LogLineFilter {
    /// Each log line that `flexi_logger` would write to the configured output channel is
    /// sent to this method.
    ///
    /// Note that the log line only appears in the configured output channel if the
    /// filter implementation forwards it to the provided `LogLineWriter`.
    ///
    /// # Errors
    ///
    /// If writing to the configured output channel fails.
    fn write(
        &self,
        now: &mut DeferredNow,
        record: &Record,
        log_line_writer: &dyn LogLineWriter,
    ) -> std::io::Result<()>;
}

/// Write out a single log line
pub trait LogLineWriter {
    /// Write out a log line to the configured output channel.
    ///
    /// # Errors
    ///
    /// If writing to the configured output channel fails.
    fn write(&self, now: &mut DeferredNow, record: &Record) -> std::io::Result<()>;
}