1 | #![cfg (feature = "registry" )] |
2 | |
3 | use std::sync::{Arc, Mutex}; |
4 | use tracing::{subscriber::with_default, Event, Metadata, Subscriber}; |
5 | use tracing_subscriber::{layer::Context, prelude::*, registry, Layer}; |
6 | |
7 | struct TrackingLayer { |
8 | enabled: bool, |
9 | event_enabled_count: Arc<Mutex<usize>>, |
10 | event_enabled: bool, |
11 | on_event_count: Arc<Mutex<usize>>, |
12 | } |
13 | |
14 | impl<C> Layer<C> for TrackingLayer |
15 | where |
16 | C: Subscriber + Send + Sync + 'static, |
17 | { |
18 | fn enabled(&self, _metadata: &Metadata<'_>, _ctx: Context<'_, C>) -> bool { |
19 | self.enabled |
20 | } |
21 | |
22 | fn event_enabled(&self, _event: &Event<'_>, _ctx: Context<'_, C>) -> bool { |
23 | *self.event_enabled_count.lock().unwrap() += 1; |
24 | self.event_enabled |
25 | } |
26 | |
27 | fn on_event(&self, _event: &Event<'_>, _ctx: Context<'_, C>) { |
28 | *self.on_event_count.lock().unwrap() += 1; |
29 | } |
30 | } |
31 | |
32 | #[test] |
33 | fn event_enabled_is_only_called_once() { |
34 | let event_enabled_count = Arc::new(Mutex::default()); |
35 | let count = event_enabled_count.clone(); |
36 | let subscriber = registry().with(TrackingLayer { |
37 | enabled: true, |
38 | event_enabled_count, |
39 | event_enabled: true, |
40 | on_event_count: Arc::new(Mutex::default()), |
41 | }); |
42 | with_default(subscriber, || { |
43 | tracing::error!("hiya!" ); |
44 | }); |
45 | |
46 | assert_eq!(1, *count.lock().unwrap()); |
47 | } |
48 | |
49 | #[test] |
50 | fn event_enabled_not_called_when_not_enabled() { |
51 | let event_enabled_count = Arc::new(Mutex::default()); |
52 | let count = event_enabled_count.clone(); |
53 | let subscriber = registry().with(TrackingLayer { |
54 | enabled: false, |
55 | event_enabled_count, |
56 | event_enabled: true, |
57 | on_event_count: Arc::new(Mutex::default()), |
58 | }); |
59 | with_default(subscriber, || { |
60 | tracing::error!("hiya!" ); |
61 | }); |
62 | |
63 | assert_eq!(0, *count.lock().unwrap()); |
64 | } |
65 | |
66 | #[test] |
67 | fn event_disabled_does_disable_event() { |
68 | let on_event_count = Arc::new(Mutex::default()); |
69 | let count = on_event_count.clone(); |
70 | let subscriber = registry().with(TrackingLayer { |
71 | enabled: true, |
72 | event_enabled_count: Arc::new(Mutex::default()), |
73 | event_enabled: false, |
74 | on_event_count, |
75 | }); |
76 | with_default(subscriber, || { |
77 | tracing::error!("hiya!" ); |
78 | }); |
79 | |
80 | assert_eq!(0, *count.lock().unwrap()); |
81 | } |
82 | |