mithril_common/test/logging/mod.rs
1//! Logging utilities for tests
2//!
3mod memory_logger;
4
5pub use memory_logger::*;
6
7/// Creates a test-specific `TestLogger` struct that can creates preconfigured logger instances.
8///
9/// This macro avoids direct `slog_async` and `slog_term` dependencies in library crates
10/// by letting dependents add them as `dev-dependencies` only.
11///
12/// ## Methods
13///
14/// - `TestLogger::stdout()` - Logger that outputs to stdout.
15/// - `TestLogger::memory()` - Logger that stores messages in memory for inspection and still outputs stdout.
16/// Returns `(Logger, MemoryDrainForTestInspector)` tuple
17///
18/// Requires: `slog`, `slog_async`, `slog_term`
19#[macro_export]
20macro_rules! define_test_logger {
21 () => {
22 /// Logger builder for tests
23 #[cfg(test)]
24 pub(crate) struct TestLogger;
25
26 #[cfg(test)]
27 mod test_logger_impl {
28 use std::io;
29
30 use slog::{Drain, Logger};
31 use slog_async::Async;
32 use slog_term::{CompactFormat, PlainDecorator, TestStdoutWriter};
33
34 use $crate::test::logging::{MemoryDrainForTest, MemoryDrainForTestInspector};
35
36 impl super::TestLogger {
37 fn from_writer<W: io::Write + Send + 'static>(writer: W) -> Async {
38 let decorator = PlainDecorator::new(writer);
39 let drain = CompactFormat::new(decorator).build().fuse();
40 Async::new(drain).build()
41 }
42
43 /// Create a logger that outputs to stdout.
44 pub(crate) fn stdout() -> Logger {
45 Logger::root(Self::from_writer(TestStdoutWriter).fuse(), slog::o!())
46 }
47
48 /// Create a logger that stores messages in memory for inspection and still outputs stdout.
49 pub(crate) fn memory() -> (Logger, MemoryDrainForTestInspector) {
50 let (memory_drain, inspector) = MemoryDrainForTest::new();
51 (Logger::root(memory_drain.fuse(), slog::o!()), inspector)
52 }
53 }
54 }
55 };
56}
57pub use define_test_logger;