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
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
//! Filter records by matching some of their keys against a sets of values while allowing
//! for records of level high enough to pass.

#[cfg(test)]
#[macro_use]
extern crate slog;

#[cfg(not(test))]
extern crate slog;

use std::collections::{HashSet, HashMap};
use std::fmt;
use std::option::Option;

use slog::KV;

// @todo: must that be thread-safe?
struct FilteringSerializer<'a> {
    pending_matches: KVFilterListFlyWeight<'a>,
    tmp_str: String,
}

impl<'a> slog::Serializer for FilteringSerializer<'a> {
    fn emit_arguments(&mut self, key: slog::Key, val: &fmt::Arguments) -> slog::Result {
        if self.pending_matches.is_empty() {
            return Ok(());
        }

        let matched = if let Some(keyvalues) = self.pending_matches.get(&key) {
            self.tmp_str.clear();
            fmt::write(&mut self.tmp_str, *val)?;

            keyvalues.contains(&self.tmp_str)
        } else {
            false
        };

        if matched {
            self.pending_matches.remove(&key);
        }

        Ok(())
    }
}

/// Must be a hashmap since we do not rely on ordered keys
type KVFilterList = HashMap<String, HashSet<String>>;

/// flyweight copy that is created upfront and given to every serializer
type KVFilterListFlyWeight<'a> = HashMap<&'a str, &'a HashSet<String>>;

/// `Drain` filtering records using list of keys and values they
/// must have unless they are of a higher level than filtering applied.
///
/// This `Drain` filters a log entry on a filtermap
/// that holds the key name in question and acceptable values
/// Key values are gathered up the whole hierarchy of inherited
/// loggers.
///
/// Example
/// =======
///
/// Logger( ... ; o!("thread" => "100");
/// log( ... ; "packet" => "send");
/// log( ... ; "packet" => "receive");
///
/// can be filtered on a map containing "thread" key component. If the
/// values contain "100" the log will be output, otherwise filtered.
/// The filtering map can contain further key "packet" and value "send".
/// With that the output for "receive" would be filtered.
///
/// More precisely
///
///   * a key is ignored until present in `KVFilterList`, otherwise an entry must
///     match for all the keys present in `KVFilterList` for any of the value given
///     for the key to pass the filter.
///   * Behavior on empty `KVFilterList` is undefined but normally anything should pass.
///
/// Usage
/// =====
///
/// Filtering in large systems that consist of multiple threads of same
/// code or have functionality of interest spread across many components,
/// modules, such as e.g. "sending packet" or "running FSM".
pub struct KVFilter<D: slog::Drain> {
    drain: D,
    filters: KVFilterList,
    level: slog::Level,
}

impl<'a, D: slog::Drain> KVFilter<D> {
    /// Create `KVFilter`
    ///
    /// * `drain` - drain to be sent to
    /// * `level` - maximum level filtered, higher levels pass by
    /// * `filters` - Hashmap of keys with lists of allowed values
    pub fn new(drain: D, level: slog::Level, filters: KVFilterList) -> Self {
        KVFilter {
            drain: drain,
            level: level,
            filters: filters,
        }
    }

    fn is_match(&self, record: &slog::Record, logger_values: &slog::OwnedKVList) -> bool {
        // Can't use chaining here, as it's not possible to cast
        // SyncSerialize to Serialize
        let mut ser = FilteringSerializer {
            pending_matches: self.filters.iter().map(|(k, v)| (k.as_str(), v)).collect(),
            tmp_str: String::new(),
        };

        record.kv().serialize(record, &mut ser).unwrap();

        if ser.pending_matches.is_empty() {
            return true;
        } else {
            logger_values.serialize(record, &mut ser).unwrap();
            ser.pending_matches.is_empty()
        }
    }
}

impl<'a, D: slog::Drain> slog::Drain for KVFilter<D> {
    type Err = D::Err;
    type Ok = Option<D::Ok>;

    fn log(&self,
           info: &slog::Record,
           logger_values: &slog::OwnedKVList)
           -> Result<Self::Ok, Self::Err> {
        println!("{:#?}", info.msg());

        if info.level() < self.level || self.is_match(info, logger_values) {
            self.drain.log(info, logger_values).map(Some)
        } else {
            Ok(None)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::KVFilter;
    use slog::{Level, Drain, Record, Logger, OwnedKVList};
    use std::collections::HashSet;
    use std::iter::FromIterator;
    use std::sync::Mutex;
    use std::fmt::Display;
    use std::fmt::Formatter;
    use std::fmt::Result as FmtResult;
    use std::io;
    use std::sync::Arc;

    const YES: &'static str = "YES";
    const NO: &'static str = "NO";

    #[derive(Debug)]
    struct StringDrain {
        output: Arc<Mutex<Vec<String>>>,
    }

    /// seriously hacked logger drain that just counts messages to make
    /// sure we have tests behaving correcly
    impl<'a> Drain for StringDrain {
        type Err = io::Error;
        type Ok = ();

        fn log(&self, info: &Record, _: &OwnedKVList) -> io::Result<()> {
            let mut lo = self.output.lock().unwrap();
            let fmt = format!("{:?}", info.msg());

            if !fmt.contains(YES) && !fmt.contains(NO) {
                panic!(fmt);
            }

            (*lo).push(fmt);

            Ok(())
        }
    }

    impl<'a> Display for StringDrain {
        fn fmt(&self, f: &mut Formatter) -> FmtResult {
            write!(f, "none")
        }
    }

    #[test]
    /// get an asserting serializer, get a couple of loggers that
    /// have different nodes, components and see whether filtering
    /// is applied properly on the derived `Logger` copies
    fn nodecomponentlogfilter() {
        {
            assert!(Level::Critical < Level::Warning);

            let out = Arc::new(Mutex::new(vec![]));

            let drain = StringDrain { output: out.clone() };

            // build some small filter
            let filter = KVFilter::new(drain,
                                       Level::Info,
                                       vec![("thread".to_string(),
                                             HashSet::from_iter(vec!["100".to_string(),
                                                                     "200".to_string()])),
                                            ("direction".to_string(),
                                             HashSet::from_iter(vec!["send".to_string(),
                                                                     "receive".to_string()]))]
                                               .into_iter()
                                               .collect());

            // Get a root logger that will log into a given drain.
            let mainlog = Logger::root(filter.fuse(), o!("version" => env!("CARGO_PKG_VERSION")));
            let sublog = mainlog.new(o!("thread" => "200", "sub" => "sub"));
            let subsublog = sublog.new(o!("direction" => "send"));
            let subsubsublog = subsublog.new(o!());

            let wrongthread = mainlog.new(o!("thread" => "400", "sub" => "sub"));

            info!(mainlog, "NO: filtered, main, no keys");
            info!(mainlog, "YES: unfiltered, on of thread matches, direction matches";
			"thread" => "100", "direction" => "send");
            info!(mainlog,
			      "YES: unfiltered, on of thread matches, direction matches, different key order";
			"direction" => "send", "thread" => "100");

            warn!(mainlog, "YES: unfiltered, higher level"); // level high enough to pass anyway

            debug!(mainlog, "NO: filtered, level to low, no keys"); // level low

            info!(mainlog, "NO: filtered, wrong thread on record";
			"thread" => "300", "direction" => "send");

            info!(wrongthread, "NO: filtered, wrong thread on sublog");

            info!(sublog, "NO: filtered sublog, missing dirction ");

            info!(sublog, "YES: unfiltered sublog with added directoin";
			"direction" => "receive");

            info!(subsubsublog,
                  "YES: unfiltered subsubsublog, direction on subsublog, thread on sublog");

            // test twice same keyword with right value will give filter match
            let stackedthreadslog = wrongthread.new(o!("thread" => "200"));

            info!(stackedthreadslog,
			      "YES: unfiltered since one of the threads matches from inherited";
			"direction" => "send");

            println!("resulting output: {:#?}", *out.lock().unwrap());

            assert_eq!(out.lock().unwrap().len(), 6);

        }
    }
}