aitia/
logging.rs

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
//! Allows for adding serialized facts to logs, to be read out later

use std::sync::Arc;

use tracing_core::Subscriber;
use tracing_subscriber::{
    fmt::{writer::MakeWriterExt, MakeWriter},
    registry::LookupSpan,
    Layer,
};

use crate::FactTraits;

pub trait FactLogTraits: FactTraits + serde::Serialize + serde::de::DeserializeOwned {}
impl<T> FactLogTraits for T where T: FactTraits + serde::Serialize + serde::de::DeserializeOwned {}

/// Add a JSON-serialized Fact to the tracing output at the Info level
#[macro_export]
macro_rules! trace {
    ($fact:expr) => {
        // Note the tracing level doesn't matter when using the AitiaWriter, but it
        // of course affects whether this will be present in the normal logs

        // XXX: because the JSON representation is wonky, especially for hashes,
        //      we also redundantly print a normal debug for better log readability
        let fact = $fact;

        let level = std::env::var("AITIA_LOG").unwrap_or("trace".to_string());
        match level.as_str() {
            "trace" => tracing::trace!(
                aitia = "json",
                ?fact,
                "<AITIA>{}</AITIA>",
                $crate::logging::LogLine::encode(fact)
            ),
            "debug" => tracing::debug!(
                aitia = "json",
                ?fact,
                "<AITIA>{}</AITIA>",
                $crate::logging::LogLine::encode(fact)
            ),
            "info" => tracing::info!(
                aitia = "json",
                ?fact,
                "<AITIA>{}</AITIA>",
                $crate::logging::LogLine::encode(fact)
            ),
            "warn" => tracing::warn!(
                aitia = "json",
                ?fact,
                "<AITIA>{}</AITIA>",
                $crate::logging::LogLine::encode(fact)
            ),
            "error" => tracing::error!(
                aitia = "json",
                ?fact,
                "<AITIA>{}</AITIA>",
                $crate::logging::LogLine::encode(fact)
            ),
            level => unimplemented!("Invalid AITIA_LOG setting: {}", level),
        }
    };
}

/// Adds encode/decode functionality to a Fact so it can be logged
pub trait LogLine: FactLogTraits {
    /// Encode as string
    fn encode(&self) -> String;
    /// Decode from string
    fn decode(s: &str) -> Self;
}

/// A JSON-encoded fact
pub trait FactLogJson: LogLine {}

impl<J: FactLogJson> LogLine for J {
    fn encode(&self) -> String {
        serde_json::to_string(self).unwrap()
    }

    fn decode(s: &str) -> Self {
        serde_json::from_str(s).unwrap()
    }
}

pub trait Log: Default {
    type Fact: LogLine;

    fn parse(line: &str) -> Option<Self::Fact> {
        regex::Regex::new("<AITIA>(.*?)</AITIA>")
            .unwrap()
            .captures(line)
            .and_then(|m| m.get(1))
            .map(|m| Self::Fact::decode(m.as_str()))
    }

    fn apply(&mut self, fact: Self::Fact);
}

/// A layer which only records logs emitted from aitia::trace!
/// This can be used to build up log state during a test run, instead of needing to
/// parse an entire completed log file, since the log file is still being written while
/// the test is running.
pub fn tracing_layer<S: Subscriber + for<'a> LookupSpan<'a>>(
    mw: impl for<'w> MakeWriter<'w> + 'static,
) -> impl Layer<S> {
    let mw = mw.with_filter(|metadata| metadata.fields().field("aitia").is_some());
    tracing_subscriber::fmt::layer()
        .with_timer(tracing_subscriber::fmt::time::UtcTime::rfc_3339())
        .with_writer(mw)
        .with_level(false)
        .with_file(true)
        .with_line_number(true)
}

#[derive(derive_more::Deref)]
pub struct AitiaSubscriber<L: Log>(Arc<parking_lot::Mutex<L>>);

impl<L: Log> Clone for AitiaSubscriber<L> {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

impl<L: Log> Default for AitiaSubscriber<L> {
    fn default() -> Self {
        Self(Arc::new(parking_lot::Mutex::new(L::default())))
    }
}

impl<L: Log> std::io::Write for AitiaSubscriber<L> {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        let mut g = self.0.lock();
        let line = String::from_utf8_lossy(buf);
        let step = L::parse(&line).unwrap();
        g.apply(step);
        Ok(buf.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use tracing_subscriber::{
        prelude::__tracing_subscriber_SubscriberExt, util::SubscriberInitExt, Registry,
    };

    use crate::{dep::DepResult, logging::AitiaSubscriber, Fact};

    use super::{tracing_layer, FactLogJson};

    #[derive(
        Debug,
        Clone,
        PartialEq,
        Eq,
        Hash,
        derive_more::Display,
        serde::Serialize,
        serde::Deserialize,
    )]
    enum TestFact {
        A(String),
        B(u32),
    }

    impl Fact for TestFact {
        type Context = ();

        fn dep(&self, _ctx: &Self::Context) -> DepResult<Self> {
            todo!()
        }

        fn check(&self, _ctx: &Self::Context) -> bool {
            todo!()
        }
    }

    impl FactLogJson for TestFact {}

    #[derive(Default)]
    struct Log(Vec<TestFact>);

    impl super::Log for Log {
        type Fact = TestFact;

        fn apply(&mut self, fact: Self::Fact) {
            self.0.push(fact)
        }
    }

    #[test]
    fn sample_log() {
        let log = AitiaSubscriber::<Log>::default();
        let log2 = log.clone();
        Registry::default()
            .with(tracing_layer(move || log2.clone()))
            .init();

        let facts = vec![
            TestFact::A("hello".to_string()),
            TestFact::B(24),
            TestFact::A("bye!".to_string()),
        ];

        for fact in facts.iter() {
            crate::trace!(fact);
        }

        {
            let ctx = log.lock();
            assert_eq!(ctx.0, facts);
        }
    }
}