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
#[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;
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(())
}
}
type KVFilterList = HashMap<String, HashSet<String>>;
type KVFilterListFlyWeight<'a> = HashMap<&'a str, &'a HashSet<String>>;
pub struct KVFilter<D: slog::Drain> {
drain: D,
filters: KVFilterList,
level: slog::Level,
}
impl<'a, D: slog::Drain> KVFilter<D> {
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 {
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>>>,
}
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]
fn nodecomponentlogfilter() {
{
assert!(Level::Critical < Level::Warning);
let out = Arc::new(Mutex::new(vec![]));
let drain = StringDrain { output: out.clone() };
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());
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");
debug!(mainlog, "NO: filtered, level to low, no keys");
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");
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);
}
}
}