Files
addr2line
adler
aho_corasick
ansi_term
atty
backtrace
base64
bincode
bitflags
bitmaps
bstr
byteorder
bytes
bytesize
cargo
cargo_platform
cfg_if
chrono
clap
color_backtrace
corpus_database
corpus_database_dsl
corpus_extractor
corpus_manager
corpus_manager_driver
corpus_queries_derive
corpus_queries_impl
crates_index
crates_io
crc32fast
crossbeam_queue
crossbeam_utils
crypto_hash
csv
csv_core
curl
curl_sys
darling
darling_core
darling_macro
datafrog
datapond
datapond_derive
datapond_macro
either
encoding_rs
env_logger
error_chain
failure
failure_derive
filetime
flate2
fnv
foreign_types
foreign_types_shared
form_urlencoded
fs2
futures
futures_channel
futures_core
futures_io
futures_macro
futures_sink
futures_task
futures_util
async_await
future
io
lock
stream
task
getrandom
gimli
git2
git2_curl
glob
globset
h2
hashbrown
heck
hex
home
http
http_body
httparse
httpdate
humantime
hyper
hyper_tls
ident_case
idna
ignore
im_rc
indexmap
iovec
ipnet
itertools
itoa
jobserver
lazy_static
lazycell
libc
libgit2_sys
libnghttp2_sys
libssh2_sys
libz_sys
lock_api
log
log_derive
matches
maybe_uninit
memchr
mime
miniz_oxide
mio
mio_uds
native_tls
nix
num_cpus
num_integer
num_traits
object
once_cell
opener
openssl
openssl_probe
openssl_sys
parking_lot
parking_lot_core
percent_encoding
pest
pin_project
pin_project_lite
pin_utils
ppv_lite86
print_stats
proc_macro2
proc_macro_error
proc_macro_error_attr
proc_macro_hack
proc_macro_nested
quick_error
quote
rand
rand_chacha
rand_core
rand_xoshiro
regex
regex_automata
regex_syntax
remove_dir_all
reqwest
rustc
rustc_demangle
rustc_hash
rustc_workspace_hack
rustfix
rustwide
ryu
same_file
scopeguard
semver
semver_parser
serde
serde_derive
serde_ignored
serde_json
serde_urlencoded
shell_escape
signal_hook_registry
simplelog
sized_chunks
slab
smallvec
socket2
strip_ansi_escapes
strsim
structopt
structopt_derive
syn
synstructure
tar
tempdir
tempfile
termcolor
textwrap
thiserror
thiserror_impl
thread_local
time
tinyvec
tinyvec_macros
tokio
future
io
loom
macros
net
park
runtime
sync
task
time
util
tokio_executor
tokio_io
tokio_native_tls
tokio_process
tokio_reactor
tokio_signal
tokio_stream
tokio_sync
tokio_util
toml
tower_service
tracing
tracing_core
tracing_futures
try_lock
typenum
ucd_trie
unicode_bidi
unicode_normalization
unicode_segmentation
unicode_width
unicode_xid
url
utf8parse
vec_map
vte
walkdir
want
xattr
  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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
//! rustwide's logging system and related utilities.

use log::{Level, LevelFilter, Log, Metadata, Record};
use std::cell::RefCell;
use std::fmt;
use std::sync::{
    atomic::{AtomicBool, Ordering},
    Arc, Mutex, Once,
};
use std::thread::LocalKey;

static INIT_LOGS: Once = Once::new();
static INITIALIZED: AtomicBool = AtomicBool::new(false);

thread_local! {
    static SCOPED: RefCell<Vec<Box<dyn SealedLog>>> = RefCell::new(Vec::new());
}

trait SealedLog {
    fn enabled(&self, metadata: &Metadata) -> bool;
    fn log(&self, record: &Record);
    fn flush(&self);
}

impl SealedLog for Box<dyn Log> {
    fn enabled(&self, metadata: &Metadata) -> bool {
        (self.as_ref() as &dyn Log).enabled(metadata)
    }

    fn log(&self, record: &Record) {
        (self.as_ref() as &dyn Log).log(record);
    }

    fn flush(&self) {
        (self.as_ref() as &dyn Log).flush();
    }
}

struct ScopedLogger {
    global: Option<Box<dyn Log>>,
    scoped: &'static LocalKey<RefCell<Vec<Box<dyn SealedLog>>>>,
}

impl ScopedLogger {
    fn new(
        global: Option<Box<dyn Log>>,
        scoped: &'static LocalKey<RefCell<Vec<Box<dyn SealedLog>>>>,
    ) -> Self {
        ScopedLogger { global, scoped }
    }

    fn each<F: FnMut(&dyn SealedLog)>(&self, mut f: F) {
        if let Some(global) = &self.global {
            f(global);
        }
        self.scoped.with(|scoped| {
            for logger in &*scoped.borrow() {
                f(logger.as_ref());
            }
        });
    }
}

impl Log for ScopedLogger {
    fn enabled(&self, metadata: &Metadata) -> bool {
        let mut result = false;
        self.each(|logger| {
            if logger.enabled(metadata) {
                result = true;
            }
        });
        result
    }

    fn log(&self, record: &Record) {
        self.each(|logger| {
            logger.log(record);
        });
    }

    fn flush(&self) {
        self.each(|logger| {
            logger.flush();
        });
    }
}

#[derive(Clone)]
#[cfg_attr(test, derive(Debug, PartialEq, Eq))]
struct StoredRecord {
    level: Level,
    message: String,
}

#[derive(Clone)]
struct InnerStorage {
    records: Vec<StoredRecord>,
    size: usize,
    truncated: bool,
}

/// Store logs captured by [`capture`] and retrieve them later.
///
/// The storage can have a maximum size and line limit, to prevent unbounded logging from exausting
/// system memory. It can be used from multiple threads at the same time. To output the stored log
/// entries you can call the `to_string()` method, which will return a string representation of
/// them.
///
/// [`capture`]: fn.capture.html
#[derive(Clone)]
pub struct LogStorage {
    inner: Arc<Mutex<InnerStorage>>,
    min_level: LevelFilter,
    max_size: Option<usize>,
    max_lines: Option<usize>,
}

impl LogStorage {
    /// Create a new log storage.
    pub fn new(min_level: LevelFilter) -> Self {
        LogStorage {
            inner: Arc::new(Mutex::new(InnerStorage {
                records: Vec::new(),
                truncated: false,
                size: 0,
            })),
            min_level,
            max_size: None,
            max_lines: None,
        }
    }

    /// Set the maximum amount of bytes stored in this struct before truncating the output.
    pub fn set_max_size(&mut self, size: usize) {
        self.max_size = Some(size);
    }

    /// Set the maximum amount of lines stored in this struct before truncating the output.
    pub fn set_max_lines(&mut self, lines: usize) {
        self.max_lines = Some(lines);
    }

    /// Duplicate the log storage, returning a new, unrelated storage with the same content and
    /// configuration.
    pub fn duplicate(&self) -> LogStorage {
        let inner = self.inner.lock().unwrap();
        LogStorage {
            inner: Arc::new(Mutex::new(inner.clone())),
            min_level: self.min_level,
            max_size: self.max_size,
            max_lines: self.max_lines,
        }
    }
}

impl SealedLog for LogStorage {
    fn enabled(&self, metadata: &Metadata) -> bool {
        metadata.level() > self.min_level
    }

    fn log(&self, record: &Record) {
        if record.level() > self.min_level {
            return;
        }
        let mut inner = self.inner.lock().unwrap();
        if inner.truncated {
            return;
        }
        if let Some(max_lines) = self.max_lines {
            if inner.records.len() >= max_lines {
                inner.records.push(StoredRecord {
                    level: Level::Warn,
                    message: "too many lines in the log, truncating it".into(),
                });
                inner.truncated = true;
                return;
            }
        }
        let message = record.args().to_string();
        if let Some(max_size) = self.max_size {
            if inner.size + message.len() >= max_size {
                inner.records.push(StoredRecord {
                    level: Level::Warn,
                    message: "too much data in the log, truncating it".into(),
                });
                inner.truncated = true;
                return;
            }
        }
        inner.size += message.len();
        inner.records.push(StoredRecord {
            level: record.level(),
            message,
        });
    }

    fn flush(&self) {}
}

impl fmt::Display for LogStorage {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let inner = self.inner.lock().unwrap();
        for record in &inner.records {
            writeln!(f, "[{}] {}", record.level, record.message)?;
        }
        Ok(())
    }
}

/// Capture all log messages emitted inside a closure.
///
/// This function will capture all the message the provided closure emitted **in the current
/// thread**, forwarding them to the provided [`LogStorage`]. rustwide's logging system needs to be
/// initialized before calling this function (either with [`init`] or [`init_with`]).
///
/// ## Example
///
/// ```
/// # rustwide::logging::init();
/// use log::{info, debug, LevelFilter};
/// use rustwide::logging::{self, LogStorage};
///
/// let storage = LogStorage::new(LevelFilter::Info);
/// logging::capture(&storage, || {
///     info!("foo");
///     debug!("bar");
/// });
///
/// assert_eq!("[INFO] foo\n", storage.to_string());
/// ```
///
/// [`LogStorage`]: struct.LogStorage.html
/// [`init`]: fn.init.html
/// [`init_with`]: fn.init_with.html
pub fn capture<R>(storage: &LogStorage, f: impl FnOnce() -> R) -> R {
    if !INITIALIZED.load(Ordering::SeqCst) {
        panic!("called capture without initializing rustwide::logging");
    }

    let storage = Box::new(storage.clone());
    SCOPED.with(|scoped| scoped.borrow_mut().push(storage));
    let result = f();
    SCOPED.with(|scoped| {
        let _ = scoped.borrow_mut().pop();
    });
    result
}

/// Initialize rustwide's logging system, enabling the use of the [`capture`] function.
///
/// This method will override any existing logger previously set and it will not show any log
/// message to the user. If you want to also add your own logger you should use the [`init_with`]
/// function.
///
/// [`capture`]: fn.capture.html
/// [`init_with`]: fn.init_with.html
pub fn init() {
    init_inner(None)
}

/// Initialize rustwide's logging system wrapping an existing logger, enabling the use of the
/// [`capture`] function.
///
/// If you don't want to add your own logger you should use the [`init`] function.
///
/// [`capture`]: fn.capture.html
/// [`init`]: fn.init.html
pub fn init_with<L: Log + 'static>(logger: L) {
    init_inner(Some(Box::new(logger)));
}

fn init_inner(logger: Option<Box<dyn Log>>) {
    INITIALIZED.store(true, Ordering::SeqCst);
    INIT_LOGS.call_once(|| {
        let multi = ScopedLogger::new(logger, &SCOPED);
        log::set_logger(Box::leak(Box::new(multi))).unwrap();
        log::set_max_level(log::LevelFilter::Trace);
    });
}

#[cfg(test)]
mod tests {
    use super::{LogStorage, StoredRecord};
    use crate::logging;
    use log::{info, trace, warn, Level, LevelFilter};

    #[test]
    fn test_log_storage() {
        logging::init();

        let storage = LogStorage::new(LevelFilter::Info);
        logging::capture(&storage, || {
            info!("an info record");
            warn!("a warn record");
            trace!("a trace record");
        });

        assert_eq!(
            storage.inner.lock().unwrap().records,
            vec![
                StoredRecord {
                    level: Level::Info,
                    message: "an info record".to_string(),
                },
                StoredRecord {
                    level: Level::Warn,
                    message: "a warn record".to_string(),
                },
            ]
        );
    }

    #[test]
    fn test_too_much_content() {
        logging::init();

        let mut storage = LogStorage::new(LevelFilter::Info);
        storage.set_max_size(1024);
        logging::capture(&storage, || {
            let content = (0..2048).map(|_| '.').collect::<String>();
            info!("{}", content);
        });

        let inner = storage.inner.lock().unwrap();
        assert_eq!(inner.records.len(), 1);
        assert!(inner
            .records
            .last()
            .unwrap()
            .message
            .contains("too much data"));
    }

    #[test]
    fn test_too_many_lines() {
        logging::init();

        let mut storage = LogStorage::new(LevelFilter::Info);
        storage.set_max_lines(100);
        logging::capture(&storage, || {
            for _ in 0..200 {
                info!("a line");
            }
        });

        let inner = storage.inner.lock().unwrap();
        assert_eq!(inner.records.len(), 101);
        assert!(inner
            .records
            .last()
            .unwrap()
            .message
            .contains("too many lines"));
    }
}