logforth_append_file/
append.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 std::io::Write;
16use std::num::NonZeroUsize;
17use std::path::PathBuf;
18use std::sync::Mutex;
19use std::sync::MutexGuard;
20
21use logforth_core::Diagnostic;
22use logforth_core::Error;
23use logforth_core::Layout;
24use logforth_core::Trap;
25use logforth_core::append::Append;
26use logforth_core::layout::PlainTextLayout;
27use logforth_core::record::Record;
28
29use crate::rolling::RollingFileWriter;
30use crate::rolling::RollingFileWriterBuilder;
31use crate::rotation::Rotation;
32
33/// A builder to configure and create an [`File`] appender.
34#[derive(Debug)]
35pub struct FileBuilder {
36    builder: RollingFileWriterBuilder,
37    layout: Box<dyn Layout>,
38}
39
40impl FileBuilder {
41    /// Create a new file appender builder.
42    pub fn new(basedir: impl Into<PathBuf>, filename: impl Into<String>) -> Self {
43        Self {
44            builder: RollingFileWriterBuilder::new(basedir, filename),
45            layout: Box::new(PlainTextLayout::default()),
46        }
47    }
48
49    /// Build the [`File`] appender.
50    ///
51    /// # Errors
52    ///
53    /// Return an error if either:
54    ///
55    /// * The log directory cannot be created.
56    /// * The configured filename is empty.
57    pub fn build(self) -> Result<File, Error> {
58        let FileBuilder { builder, layout } = self;
59        let writer = builder.build()?;
60        Ok(File::new(writer, layout))
61    }
62
63    /// Set the layout for the logs.
64    ///
65    /// Default to [`PlainTextLayout`].
66    ///
67    /// # Examples
68    ///
69    /// ```
70    /// use logforth_append_file::FileBuilder;
71    /// use logforth_layout_json::JsonLayout;
72    ///
73    /// let builder = FileBuilder::new("my_service", "my_app");
74    /// builder.layout(JsonLayout::default());
75    /// ```
76    pub fn layout(mut self, layout: impl Into<Box<dyn Layout>>) -> Self {
77        self.layout = layout.into();
78        self
79    }
80
81    /// Set the trap for the file writer.
82    ///
83    /// Default to [`DefaultTrap`].
84    ///
85    /// # Examples
86    ///
87    /// ```
88    /// use logforth_append_file::FileBuilder;
89    /// use logforth_core::trap::DefaultTrap;
90    ///
91    /// let builder = FileBuilder::new("my_service", "my_app");
92    /// builder.trap(DefaultTrap::default());
93    /// ```
94    pub fn trap(mut self, trap: impl Into<Box<dyn Trap>>) -> Self {
95        self.builder = self.builder.trap(trap);
96        self
97    }
98
99    /// Set the rotation strategy to roll over log files minutely.
100    pub fn rollover_minutely(mut self) -> Self {
101        self.builder = self.builder.rotation(Rotation::Minutely);
102        self
103    }
104
105    /// Set the rotation strategy to roll over log files hourly.
106    pub fn rollover_hourly(mut self) -> Self {
107        self.builder = self.builder.rotation(Rotation::Hourly);
108        self
109    }
110
111    /// Set the rotation strategy to roll over log files daily at 00:00 in the local time zone.
112    pub fn rollover_daily(mut self) -> Self {
113        self.builder = self.builder.rotation(Rotation::Daily);
114        self
115    }
116
117    /// Set the rotation strategy to roll over log files if the current log file exceeds the given
118    /// size.
119    ///
120    /// If any time-based rotation strategy is set, the size-based rotation will be checked on the
121    /// current log file after the time-based rotation check.
122    pub fn rollover_size(mut self, n: NonZeroUsize) -> Self {
123        self.builder = self.builder.max_file_size(n);
124        self
125    }
126
127    /// Set the filename suffix.
128    pub fn filename_suffix(mut self, suffix: impl Into<String>) -> Self {
129        self.builder = self.builder.filename_suffix(suffix);
130        self
131    }
132
133    /// Set the maximum number of log files to keep.
134    pub fn max_log_files(mut self, n: NonZeroUsize) -> Self {
135        self.builder = self.builder.max_log_files(n);
136        self
137    }
138}
139
140/// An appender that writes log records to rolling files.
141#[derive(Debug)]
142pub struct File {
143    writer: Mutex<RollingFileWriter>,
144    layout: Box<dyn Layout>,
145}
146
147impl File {
148    fn new(writer: RollingFileWriter, layout: Box<dyn Layout>) -> Self {
149        let writer = Mutex::new(writer);
150        Self { writer, layout }
151    }
152
153    fn writer(&self) -> MutexGuard<'_, RollingFileWriter> {
154        self.writer.lock().unwrap_or_else(|e| e.into_inner())
155    }
156}
157
158impl Append for File {
159    fn append(&self, record: &Record, diags: &[Box<dyn Diagnostic>]) -> Result<(), Error> {
160        let mut bytes = self.layout.format(record, diags)?;
161        bytes.push(b'\n');
162        let mut writer = self.writer();
163        writer.write_all(&bytes).map_err(Error::from_io_error)?;
164        Ok(())
165    }
166
167    fn flush(&self) -> Result<(), Error> {
168        let mut writer = self.writer();
169        writer.flush().map_err(Error::from_io_error)?;
170        Ok(())
171    }
172}
173
174impl Drop for File {
175    fn drop(&mut self) {
176        let writer = self.writer.get_mut().unwrap_or_else(|e| e.into_inner());
177        let _ = writer.flush();
178    }
179}