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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
//! A [`log::Log`] implementation which dynamically reloads inner loggers.
//!
//! [`ReloadLog`] wraps an inner logger and provides a [`ReloadHandle`] to
//! dynamically replace or modify the inner logger.
//!
//! This allows programs to dynamically change the log level or log target at
//! runtime.

#![deny(warnings, clippy::all, missing_docs)]
#![forbid(unsafe_code)]

use std::sync::{Arc, RwLock, Weak};

use log::Log;
use thiserror::Error;

/// Filter an underlying logger by a given max level.
///
/// Only forward log events whose log level is smaller or equal than the
/// configured level to the underlying logger.
#[derive(Debug)]
pub struct LevelFilter<T> {
    level: log::Level,
    logger: T,
}

impl<T> LevelFilter<T> {
    /// Create a new level filter with the given max `level` around the given `logger`.
    pub fn new(level: log::Level, logger: T) -> Self {
        Self { level, logger }
    }

    /// Get the current log level.
    pub fn level(&self) -> log::Level {
        self.level
    }

    /// Change the maximum log level.
    pub fn set_level(&mut self, level: log::Level) {
        self.level = level;
    }

    fn level_passes(&self, metadata: &log::Metadata) -> bool {
        metadata.level() <= self.level
    }

    /// Get a reference to the inner unfiltered logger.
    pub fn inner(&self) -> &T {
        &self.logger
    }

    /// Replace the inner logger.
    pub fn set_inner(&mut self, logger: T) {
        self.logger = logger;
    }
}

impl<T: Log> log::Log for LevelFilter<T> {
    /// Wether this logger is enabled.
    ///
    /// Return `true` if the log level in `metadata` is less then the level of
    /// the given `metadata`, and the underlying logger is enabled.
    fn enabled(&self, metadata: &log::Metadata) -> bool {
        self.level_passes(metadata) && self.logger.enabled(metadata)
    }

    /// Forward a log `record` to the underlying logger if it passes the level filter.
    fn log(&self, record: &log::Record) {
        if self.level_passes(record.metadata()) {
            self.logger.log(record)
        }
    }

    /// Flush the underlying logger.
    fn flush(&self) {
        self.logger.flush();
    }
}

/// A logger which can dynamically reload an inner logger.
///
/// This enables applications to dyanmically change e.g. the log output or
/// log level.
#[derive(Debug)]
pub struct ReloadLog<T> {
    underlying: Arc<RwLock<T>>,
}

impl<T> ReloadLog<T> {
    /// Create a new reloadable logger over the given `logger`.
    pub fn new(logger: T) -> Self {
        Self {
            underlying: Arc::new(RwLock::new(logger)),
        }
    }

    /// Obtain a handle to reload or modify the inner logger.
    pub fn handle(&self) -> ReloadHandle<T> {
        ReloadHandle {
            underlying: Arc::downgrade(&self.underlying),
        }
    }
}

impl<T: Log> Log for ReloadLog<T> {
    /// Whether the underlying logger is enabled.
    ///
    /// Always return `false` if the [`RwLock`] protecting the inner logger is poisoned,
    /// because we can't trust that the inner logger is valid if a panic occurred
    /// while it was modified, so we indicate that this logger shouldn't be used at all.
    fn enabled(&self, metadata: &log::Metadata) -> bool {
        self.underlying
            .read()
            .map_or(false, |l| l.enabled(metadata))
    }

    /// Log the given `record` with the inner logger.
    ///
    /// If the [`RwLock`] protecting the inner logger is poisoned do nothing,
    /// because we can't trust that the inner logger is valid if a panic occurred
    /// while it was modified.  The `record` is likely lost in this case.
    fn log(&self, record: &log::Record) {
        // We can't reasonably do anything if the lock is poisoned so we ignore the result
        let _ = self.underlying.read().map(|l| l.log(record));
    }

    /// Flush the inner logger
    ///
    /// If the [`RwLock`] protecting the inner logger is poisoned do nothing,
    /// because we can't trust that the inner logger is valid if a panic occurred
    /// while it was modified.
    fn flush(&self) {
        // We can't reasonably do anything if the lock is poisoned so we ignore the result
        let _ = self.underlying.read().map(|l| l.flush());
    }
}

/// An error which occurred while reloading the logger.
#[derive(Debug, Clone, Copy, Error)]
pub enum ReloadError {
    /// The logger referenced by the reload handle was dropped meanwhile.
    #[error("Referenced logger was dropped")]
    Gone,
    /// The lock protecting the inner logger referenced by the reload is poisoned.
    ///
    /// Note that this is an error because we currently can't recover from a
    /// poisoned [`RwLock`] in stable rust, as [`RwLock::clear_poison`] is still
    /// experimental.
    ///
    /// Once this method stabilizes reloading can simply overwrite any poisoned
    /// data and clear the poison flag to resume logging.  At this point this
    /// error condition will be removed.
    ///
    /// See <https://github.com/rust-lang/rust/issues/96469> for stabilization of
    /// [`RwLock::clear_poison`].
    #[error("Lock poisoned")]
    Poisoned,
}

/// A handle to reload a logger inside a [`ReloadLog`].
#[derive(Debug, Clone)]
pub struct ReloadHandle<T> {
    underlying: Weak<RwLock<T>>,
}

impl<T> ReloadHandle<T> {
    /// Replace the inner logger.
    ///
    /// This replaces the inner logger of the referenced [`ReloadLog`] with the given `logger`.
    pub fn replace(&self, logger: T) -> Result<(), ReloadError> {
        let lock = self.underlying.upgrade().ok_or(ReloadError::Gone)?;
        // TODO: Overwrite and clear poison, once clear_poison() is stabilized
        // See https://github.com/rust-lang/rust/issues/96469
        let mut guard = lock.write().map_err(|_| ReloadError::Poisoned)?;
        *guard = logger;
        Ok(())
    }

    /// Modify the inner logger.
    ///
    /// Call the given function with a mutable reference to the logger.  Note that
    /// a lock is held while invoking `f`, so no log messages will be processed
    /// until `f` returns.
    ///
    /// If `f` panics this lock gets poisoned which effectively disables the logger.
    pub fn modify<F>(&self, f: F) -> Result<(), ReloadError>
    where
        F: FnOnce(&mut T),
    {
        let lock = self.underlying.upgrade().ok_or(ReloadError::Gone)?;
        // TODO: Overwrite and clear poison, once clear_poison() is stabilized
        // See https://github.com/rust-lang/rust/issues/96469
        let mut guard = lock.write().map_err(|_| ReloadError::Poisoned)?;
        f(&mut *guard);
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use crate::{LevelFilter, ReloadLog};
    use log::{Log, Record};
    use similar_asserts::assert_eq;
    use std::sync::{Arc, Mutex};

    struct CollectMessages {
        messages: Mutex<Vec<String>>,
    }

    impl CollectMessages {
        fn new() -> Self {
            Self {
                messages: Mutex::new(Vec::new()),
            }
        }
    }

    impl Log for CollectMessages {
        fn enabled(&self, _metadata: &log::Metadata) -> bool {
            true
        }

        fn log(&self, record: &log::Record) {
            let mut guard = self.messages.try_lock().unwrap();
            guard.push(format!("{}", record.args()));
        }

        fn flush(&self) {}
    }

    #[test]
    fn sanity_check_log_level_ordering() {
        use log::Level;

        assert!(Level::Error <= Level::Warn);
        assert!(Level::Warn <= Level::Warn);
        assert!(Level::Debug >= Level::Warn);
    }

    #[test]
    fn level_filter() {
        let collect_logs = Arc::new(CollectMessages::new());
        let mut filter = LevelFilter::new(log::Level::Warn, collect_logs.clone());

        for level in log::Level::iter() {
            filter.log(
                &Record::builder()
                    .level(level)
                    .args(format_args!("{level}"))
                    .build(),
            );
        }
        let mut messages = collect_logs.messages.try_lock().unwrap();
        assert_eq!(*messages, vec!["ERROR", "WARN"]);
        messages.clear();
        drop(messages);

        filter.set_level(log::Level::Debug);

        for level in log::Level::iter() {
            filter.log(
                &Record::builder()
                    .level(level)
                    .args(format_args!("{level}"))
                    .build(),
            );
        }
        let messages = collect_logs.messages.try_lock().unwrap();
        assert_eq!(*messages, &["ERROR", "WARN", "INFO", "DEBUG"]);
    }

    #[test]
    fn reloadlog_replace() {
        let collect_logs_1 = Arc::new(CollectMessages::new());
        let collect_logs_2 = Arc::new(CollectMessages::new());

        let reload_log = ReloadLog::new(collect_logs_1.clone());
        let reload_handle = reload_log.handle();

        reload_log.log(&Record::builder().args(format_args!("Message 1")).build());

        reload_handle.replace(collect_logs_2.clone()).unwrap();

        reload_log.log(&Record::builder().args(format_args!("Message 2")).build());

        let messages_1 = collect_logs_1.messages.try_lock().unwrap();
        let messages_2 = collect_logs_2.messages.try_lock().unwrap();
        assert_eq!(*messages_1, &["Message 1"]);
        assert_eq!(*messages_2, &["Message 2"]);
    }

    #[test]
    fn reloadlog_modify() {
        let collect_logs = Arc::new(CollectMessages::new());

        let reload_log = ReloadLog::new(collect_logs.clone());
        let reload_handle = reload_log.handle();

        reload_log.log(&Record::builder().args(format_args!("Message 1")).build());
        let messages = collect_logs.messages.try_lock().unwrap();
        assert_eq!(*messages, &["Message 1"]);
        drop(messages);

        // Clear the message store through the reload handle.
        reload_handle
            .modify(|l| l.messages.try_lock().unwrap().clear())
            .unwrap();

        // At this point the first message doesn't appear anymore.
        reload_log.log(&Record::builder().args(format_args!("Message 2")).build());
        let messages = collect_logs.messages.try_lock().unwrap();
        assert_eq!(*messages, &["Message 2"]);
    }
}