1 | use tracing::Level; |
2 | use tracing_mock::{expect, layer}; |
3 | use tracing_subscriber::{field::Visit, layer::Filter, prelude::*}; |
4 | |
5 | struct FilterEvent; |
6 | |
7 | impl<S> Filter<S> for FilterEvent { |
8 | fn enabled( |
9 | &self, |
10 | _meta: &tracing::Metadata<'_>, |
11 | _cx: &tracing_subscriber::layer::Context<'_, S>, |
12 | ) -> bool { |
13 | true |
14 | } |
15 | |
16 | fn event_enabled( |
17 | &self, |
18 | event: &tracing::Event<'_>, |
19 | _cx: &tracing_subscriber::layer::Context<'_, S>, |
20 | ) -> bool { |
21 | struct ShouldEnable(bool); |
22 | impl Visit for ShouldEnable { |
23 | fn record_bool(&mut self, field: &tracing_core::Field, value: bool) { |
24 | if field.name() == "enable" { |
25 | self.0 = value; |
26 | } |
27 | } |
28 | |
29 | fn record_debug( |
30 | &mut self, |
31 | _field: &tracing_core::Field, |
32 | _value: &dyn core::fmt::Debug, |
33 | ) { |
34 | } |
35 | } |
36 | let mut should_enable = ShouldEnable(false); |
37 | event.record(&mut should_enable); |
38 | should_enable.0 |
39 | } |
40 | } |
41 | |
42 | #[test] |
43 | fn per_layer_event_field_filtering() { |
44 | let (expect, handle) = layer::mock() |
45 | .event(expect::event().at_level(Level::TRACE)) |
46 | .event(expect::event().at_level(Level::INFO)) |
47 | .only() |
48 | .run_with_handle(); |
49 | |
50 | let _subscriber = tracing_subscriber::registry() |
51 | .with(expect.with_filter(FilterEvent)) |
52 | .set_default(); |
53 | |
54 | tracing::trace!(enable = true, "hello trace" ); |
55 | tracing::debug!("hello debug" ); |
56 | tracing::info!(enable = true, "hello info" ); |
57 | tracing::warn!(enable = false, "hello warn" ); |
58 | tracing::error!("hello error" ); |
59 | |
60 | handle.assert_finished(); |
61 | } |
62 | |