logforth_core/append/
testing.rs

1// Copyright 2024 FastLabs Developers
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use crate::Diagnostic;
16use crate::Error;
17use crate::Layout;
18use crate::append::Append;
19use crate::layout::PlainTextLayout;
20use crate::record::Record;
21
22/// An appender that writes log records that can be captured by a test harness (like `cargo test`),
23/// and thus the outputs are suppressed unless `--nocapture` or `--show-output` is specified.
24///
25/// # Examples
26///
27/// ```
28/// use logforth_core::append::Testing;
29///
30/// let test_appender = Testing::default();
31/// ```
32#[derive(Debug)]
33pub struct Testing {
34    layout: Box<dyn Layout>,
35}
36
37impl Default for Testing {
38    fn default() -> Self {
39        Self {
40            layout: Box::new(PlainTextLayout::default()),
41        }
42    }
43}
44
45impl Testing {
46    /// Set the layout for the [`Testing`] appender.
47    ///
48    /// Default to [`PlainTextLayout`].
49    ///
50    /// # Examples
51    ///
52    /// ```
53    /// use logforth_core::append::Testing;
54    /// use logforth_core::layout::PlainTextLayout;
55    ///
56    /// let test_appender = Testing::default().with_layout(PlainTextLayout::default());
57    /// ```
58    pub fn with_layout(mut self, layout: impl Into<Box<dyn Layout>>) -> Self {
59        self.layout = layout.into();
60        self
61    }
62}
63
64impl Append for Testing {
65    fn append(&self, record: &Record, diags: &[Box<dyn Diagnostic>]) -> Result<(), Error> {
66        let bytes = self.layout.format(record, diags)?;
67        eprintln!("{}", String::from_utf8_lossy(&bytes));
68        Ok(())
69    }
70
71    fn flush(&self) -> Result<(), Error> {
72        // nothing to flush for eprintln
73        Ok(())
74    }
75}