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
#![cfg_attr(test, allow(non_snake_case))]
mod readme_doctests;

/// This macro runs the given code block, collects any tracing Events emitted, and returns them as a
/// `Vec<tracing_assert_core::Event>`.
///
/// Invoke it with
/// ```rust
/// use tracing;
/// use tracing_assert_core::Event;
/// use tracing_assert_macros::tracing_capture_events;
///
/// fn foo() {
///     tracing::trace!("my event data!");
/// }
///
/// let events: Vec<Event> = tracing_capture_events!({foo()});
/// ```
#[macro_export]
macro_rules! tracing_capture_events {
    ( $code_under_test:block ) => {{
        let events = {
            use tracing_assert_core::{
                lazy_static::lazy_static,
                tracing_subscriber::{self, layer::SubscriberExt},
                Event, Layer, Notification,
            };

            lazy_static! {
                static ref LAYER: Layer<Notification> = Layer::new();
            }

            let subscriber = tracing_subscriber::FmtSubscriber::builder()
                .with_test_writer()
                .with_max_level(tracing::Level::TRACE)
                .pretty()
                .finish()
                .with(&*LAYER);

            tracing::subscriber::with_default(subscriber, || $code_under_test);

            let events: Vec<Event> = LAYER.drain_events();
            events
        };
        events
    }};
}

/// This macro runs the given code block, collects any tracing Events emitted, and returns the
/// Field/Value pairs carried by each event.
///
/// This utility macro is useful for callers only caring about the custom Field/Value data, and not necessarily the
/// complete `Event` object.
///
/// Use it with
/// ```rust
/// use tracing;
/// use tracing_assert_core::FieldValueMap;
/// use tracing_assert_macros::tracing_capture_event_fields;
///
/// fn foo() {
///     tracing::trace!("my event data!");
/// }
///
/// let events: Vec<FieldValueMap> = tracing_capture_event_fields!({foo()});
/// ```
#[macro_export]
macro_rules! tracing_capture_event_fields {
    ( $code_under_test:block ) => {{
        let events = {
            use tracing_assert_core::FieldValueMap;

            let events = $crate::tracing_capture_events!({ $code_under_test });
            let events: Vec<FieldValueMap> =
                events.into_iter().map(|e| e.fields().clone()).collect();
            events
        };
        events
    }};
}

#[cfg(test)]
mod tests {
    use super::*;
    use tracing_assert_core::{debug_fmt_ext::DebugFmtExt, FieldValueMap};

    #[derive(Debug)]
    pub enum MyDomainLogEvent {
        Foo,
        Bar,
    }

    #[test]
    fn tracing_capture_event_fields__captures_multiple_custom_structs_per_event() {
        // Given
        fn emit_2_complex_payload_events() {
            tracing::info_span!("outermost span").in_scope(|| {
                tracing::trace!(message1 = ?MyDomainLogEvent::Foo, message2 = ?MyDomainLogEvent::Bar);
                tracing::trace!(arbitrary_key = ?MyDomainLogEvent::Bar);
            });
        }

        // When
        let events = tracing_capture_event_fields!({
            emit_2_complex_payload_events();
        });

        // Then
        let expected_events: Vec<Vec<(String, String)>> = vec![
            vec![
                ("message1".into(), MyDomainLogEvent::Foo.debug_fmt()),
                ("message2".into(), MyDomainLogEvent::Bar.debug_fmt()),
            ],
            vec![("arbitrary_key".into(), MyDomainLogEvent::Bar.debug_fmt())],
        ];

        assert_eq!(events, expected_events);
    }

    #[test]
    fn tracing_capture_event_fields__captures_debug_repr_of_custom_event_struct() {
        // Given
        fn emit_2_complex_payload_events() {
            // Only emit one field per event. Field should be typed Domain event
            // Always use debug representation of Event type with the `?` prefix
            tracing::trace!(message = ?MyDomainLogEvent::Foo);
            // Use consistent key (e.g. "message")
            tracing::trace!(message = ?MyDomainLogEvent::Bar);
        }

        // When
        let events = tracing_capture_event_fields!({
            emit_2_complex_payload_events();
        });

        // Then
        let expected_events: Vec<Vec<(String, String)>> = vec![
            vec![("message".into(), MyDomainLogEvent::Foo.debug_fmt())],
            vec![("message".into(), MyDomainLogEvent::Bar.debug_fmt())],
        ];

        assert_eq!(events, expected_events);
    }

    #[test]
    fn tracing_capture_events__can_collect_fields_values_off_of_returned_event() {
        // Given
        fn emit_2_complex_payload_events() {
            tracing::info_span!("outermost span").in_scope(|| {
                tracing::trace!(message1 = ?MyDomainLogEvent::Foo, message2 = ?MyDomainLogEvent::Bar);
                tracing::trace!(arbitrary_key = ?MyDomainLogEvent::Bar);
            });
        }

        // When
        let events = tracing_capture_events!({
            emit_2_complex_payload_events();
        });

        // Then
        let expected_events: Vec<Vec<(String, String)>> = vec![
            vec![
                ("message1".into(), MyDomainLogEvent::Foo.debug_fmt()),
                ("message2".into(), MyDomainLogEvent::Bar.debug_fmt()),
            ],
            vec![("arbitrary_key".into(), MyDomainLogEvent::Bar.debug_fmt())],
        ];

        let events: Vec<FieldValueMap> = events.into_iter().map(|e| e.fields().clone()).collect();

        // Assert list of events come back with expected fields
        assert_eq!(events, expected_events);
    }
}