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
//! Offers functionality to set an event on a [`LogId`] and capture its content in a [`LogIdMap`].

use crate::{
    id_entry::{LogIdEntry, Origin},
    id_map::{LogIdMap, LOG_ID_MAP},
    log_id::{EventLevel, LogId},
};

/// Trait to use [`LogId`] for tracing.
pub trait LogIdTracing {
    /// Set an event for a [`LogId`] using the global [`LogIdMap`] reference [`LOG_ID_MAP`].
    ///
    /// # Arguments
    ///
    /// * `msg` - main message that is set for this log-id (should be a user-centered event description)
    /// * `filename` - name of the source file where the event is set (Note: use `file!()`)
    /// * `line_nr` - line number where the event is set (Note: use `line!()`)
    fn set_event<'a>(self, msg: &str, filename: &str, line_nr: u32) -> MappedLogId<'a>;

    /// Set an event for a [`LogId`] using a given [`LogIdMap`].
    ///
    /// # Arguments
    ///
    /// * `log_map` - the map the log-id and all its addons are captured in
    /// * `msg` - main message that is set for this log-id (should be a user-centered event description)
    /// * `filename` - name of the source file where the event is set (Note: use `file!()`)
    /// * `line_nr` - line number where the event is set (Note: use `line!()`)
    fn set_event_with<'a>(
        self,
        log_map: &'a LogIdMap,
        msg: &str,
        filename: &str,
        line_nr: u32,
    ) -> MappedLogId<'a>;

    /// Set an event for a [`LogId`] **without** adding it to a [`LogIdMap`].
    ///
    /// # Arguments
    ///
    /// * `msg` - main message that is set for this log-id (should be a user-centered event description)
    /// * `filename` - name of the source file where the event is set (Note: use `file!()`)
    /// * `line_nr` - line number where the event is set (Note: use `line!()`)
    fn set_silent_event<'a>(self, msg: &str, filename: &str, line_nr: u32) -> MappedLogId<'a>;
}

/// Traces a [`LogIdEntry`] creation.
fn trace_entry_creation(id: LogId, msg: &str, filename: &str, line_nr: u32) -> LogIdEntry {
    let id_entry = LogIdEntry::new(id, msg, filename, line_nr);

    // Note: It is not possible to set `target` via parameter, because it requires `const`
    // Same goes for `level` for the `event` macro => match and code duplication needed
    match id_entry.level {
        EventLevel::Error => tracing::error!("{}: {}", id, msg),
        EventLevel::Warn => tracing::warn!("{}: {}", id, msg),
        EventLevel::Info => tracing::info!("{}: {}", id, msg),
        EventLevel::Debug => tracing::debug!("{}: {}", id, msg),
    }

    tracing::trace!("{}(origin): {}", id, String::from(&id_entry.origin));

    id_entry
}

impl LogIdTracing for LogId {
    fn set_event<'a>(self, msg: &str, filename: &str, line_nr: u32) -> MappedLogId<'a> {
        self.set_event_with(&*LOG_ID_MAP, msg, filename, line_nr)
    }

    fn set_event_with<'a>(
        self,
        log_map: &'a LogIdMap,
        msg: &str,
        filename: &str,
        line_nr: u32,
    ) -> MappedLogId<'a> {
        let entry = trace_entry_creation(self, msg, filename, line_nr);
        let origin = entry.origin.clone();

        let update_map = log_map.map.write();
        if let Ok(mut map) = update_map {
            match map.get_mut(&self) {
                Some(entries) => entries.push(entry),
                None => {
                    map.insert(self, [entry].into());
                }
            };
        }

        MappedLogId {
            id: self,
            origin,
            map: Some(log_map),
        }
    }

    fn set_silent_event<'a>(self, msg: &str, filename: &str, line_nr: u32) -> MappedLogId<'a> {
        let id_entry = trace_entry_creation(self, msg, filename, line_nr);

        MappedLogId {
            id: id_entry.id,
            origin: id_entry.origin,
            map: None,
        }
    }
}

/// Struct linking a [`LogId`] to the map the entry for the ID was added to.
pub struct MappedLogId<'a> {
    id: LogId,
    origin: Origin,
    map: Option<&'a LogIdMap>,
}

impl<'a> Drop for MappedLogId<'a> {
    /// [`MappedLogId`] is finalized on drop.
    fn drop(&mut self) {
        self.finalize();
    }
}

impl<'a> MappedLogId<'a> {
    /// Returns the [`LogId`] of the [`MappedLogId`].
    pub fn id(&self) -> LogId {
        self.id
    }

    /// Add a message describing the cause for this log-id
    pub fn add_cause(self, msg: &str) -> Self {
        tracing::info!("{}(cause): {}", self.id, msg);

        if let Some(log_map) = self.map {
            let update_map = log_map.map.write();
            if let Ok(mut map) = update_map {
                match map.get_mut(&self.id) {
                    Some(entries) => {
                        if let Some(last) = entries.last_mut() {
                            last.add_cause(msg.to_string());
                        };
                    }
                    None => {
                        tracing::warn!(
                            "Got cause=\"{}\" for log-id={}, but no base for log-id was set!",
                            msg,
                            self.id
                        )
                    }
                };
            }
        }

        self
    }

    /// Add an info message for this log-id
    pub fn add_info(self, msg: &str) -> Self {
        tracing::info!("{}(addon): {}", self.id, msg);
        add_addon_to_map(&self, msg, &tracing::Level::INFO);
        self
    }

    /// Add a debug message for this log-id
    pub fn add_debug(self, msg: &str) -> Self {
        tracing::debug!("{}(addon): {}", self.id, msg);
        add_addon_to_map(&self, msg, &tracing::Level::DEBUG);
        self
    }

    /// Add a trace message for this log-id
    pub fn add_trace(self, msg: &str) -> Self {
        tracing::trace!("{}(addon): {}", self.id, msg);
        add_addon_to_map(&self, msg, &tracing::Level::TRACE);
        self
    }

    /// Finalizing a [`MappedLogId`] marks the map entry that
    /// no more information will be added to it.
    ///
    /// Besides the [`LogId`], also the [`Origin`] of the [`LogIdEntry`] is compared for identification.
    pub fn finalize(&self) -> LogId {
        let mut finalized = false;
        if let Some(log_map) = self.map {
            if let Ok(mut map) = log_map.map.write() {
                if let Some(entries) = map.get_mut(&self.id) {
                    for entry in entries {
                        if entry.origin == self.origin {
                            entry.finalize();
                            finalized = true;
                        }
                    }
                }
            }
            // flag used to shorten access to write-lock
            if finalized {
                if let Ok(mut last_id) = log_map.last_finalized_id.write() {
                    *last_id = self.id;
                }
            }
        }

        self.id
    }
}

fn add_addon_to_map(mapped_id: &MappedLogId, msg: &str, level: &tracing::Level) {
    if let Some(log_map) = mapped_id.map {
        let update_map = log_map.map.write();
        if let Ok(mut map) = update_map {
            match map.get_mut(&mapped_id.id) {
                Some(entries) => {
                    if let Some(last) = entries.last_mut() {
                        last.add_addon(level, msg.to_string());
                    };
                }
                None => {
                    tracing::warn!(
                        "Got addon=\"{}\" for log-id={}, but no base for log-id was set!",
                        msg,
                        mapped_id.id
                    )
                }
            };
        }
    }
}