tracing_rolling_file/
lib.rs

1//! A rolling file appender with customizable rolling conditions.
2//! Includes built-in support for rolling conditions on date/time
3//! (daily, hourly, every minute) and/or size.
4//!
5//! Follows a Debian-style naming convention for logfiles,
6//! using basename, basename.1, ..., basename.N where N is
7//! the maximum number of allowed historical logfiles.
8//!
9//! This is useful to combine with the tracing crate and
10//! tracing_appender::non_blocking::NonBlocking -- use it
11//! as an alternative to tracing_appender::rolling::RollingFileAppender.
12//!
13//! # Examples
14//!
15//! ```rust
16//! # fn docs() {
17//! # use tracing_rolling_file::*;
18//! let file_appender = RollingFileAppenderBase::new(
19//!     "/var/log/myprogram",
20//!     RollingConditionBase::new().daily(),
21//!     9
22//! ).unwrap();
23//! # }
24//! ```
25//!
26//! ### Builder
27//!
28//! To simplify the creation of a `RollingFileAppenderBase`, an instance can be built as per the example below.
29//!
30//! ```rust
31//! use tracing_rolling_file::*;
32//!
33//! let builder = RollingFileAppenderBase::builder();
34//! let appender = builder
35//!     .filename(String::from("my_app.log"))
36//!     .max_filecount(10)
37//!     .condition_max_file_size(100)
38//!     .build()
39//!     .unwrap();
40//! ```
41//!
42//! ### Non-blocking support
43//!
44//! To combine the `tracing_appender::non_blocking::NonBlocking` functionality,
45//! the feature needs to be enabled in Cargo.toml, i.e.
46//!
47//! ```toml
48//! [dependencies]
49//! tracing-rolling-file = { version = "0.1.3", features = ["non-blocking"] }
50//! ```
51//!
52//! Once enabled, you can use the method `get_non_blocking_appender` to generate
53//! a non-blocking version of the RollingFileAppenderBase.
54//!
55//! ```rust
56//! # #[cfg(feature = "non-blocking")]
57//! # fn docs() -> Result<(), Box<dyn std::error::Error>> {
58//! use tracing_rolling_file::*;
59//!
60//! let file_appender = RollingFileAppenderBase::new(
61//!     "/var/log/myprogram",
62//!     RollingConditionBase::new().daily(),
63//!     9
64//! )?;
65//! let (non_blocking, _guard) = file_appender.get_non_blocking_appender();
66//! # Ok(())
67//! # }
68//! ```
69#![deny(warnings)]
70
71use chrono::prelude::*;
72use std::{
73    convert::TryFrom,
74    fs::{self, File, OpenOptions},
75    io::{self, BufWriter, Write},
76    path::Path,
77};
78
79/// Determines when a file should be "rolled over".
80pub trait RollingCondition {
81    /// Determine and return whether or not the file should be rolled over.
82    fn should_rollover(&mut self, now: &DateTime<Local>, current_filesize: u64) -> bool;
83}
84
85/// Determines how often a file should be rolled over
86#[derive(Copy, Clone, Debug, Eq, PartialEq)]
87pub enum RollingFrequency {
88    EveryDay,
89    EveryHour,
90    EveryMinute,
91}
92
93impl RollingFrequency {
94    /// Calculates a datetime that will be different if data should be in
95    /// different files.
96    pub fn equivalent_datetime(&self, dt: &DateTime<Local>) -> DateTime<Local> {
97        let (year, month, day) = (dt.year(), dt.month(), dt.day());
98        let (hour, min, sec) = match self {
99            RollingFrequency::EveryDay => (0, 0, 0),
100            RollingFrequency::EveryHour => (dt.hour(), 0, 0),
101            RollingFrequency::EveryMinute => (dt.hour(), dt.minute(), 0),
102        };
103        Local.with_ymd_and_hms(year, month, day, hour, min, sec).unwrap()
104    }
105}
106
107/// Writes data to a file, and "rolls over" to preserve older data in
108/// a separate set of files. Old files have a Debian-style naming scheme
109/// where we have base_filename, base_filename.1, ..., base_filename.N
110/// where N is the maximum number of rollover files to keep.
111#[derive(Debug)]
112pub struct RollingFileAppender<RC>
113where
114    RC: RollingCondition,
115{
116    condition: RC,
117    filename: String,
118    max_filecount: usize,
119    current_filesize: u64,
120    writer_opt: Option<BufWriter<File>>,
121}
122
123impl<RC> RollingFileAppender<RC>
124where
125    RC: RollingCondition,
126{
127    /// Creates a new rolling file appender with the given condition.
128    /// The filename parent path must already exist.
129    pub fn new(filename: impl AsRef<Path>, condition: RC, max_filecount: usize) -> io::Result<RollingFileAppender<RC>> {
130        let filename = filename.as_ref().to_str().unwrap().to_string();
131        let mut appender = RollingFileAppender {
132            condition,
133            filename,
134            max_filecount,
135            current_filesize: 0,
136            writer_opt: None,
137        };
138        // Fail if we can't open the file initially...
139        appender.open_writer_if_needed()?;
140        Ok(appender)
141    }
142
143    /// Determines the final filename, where n==0 indicates the current file
144    fn filename_for(&self, n: usize) -> String {
145        let f = self.filename.clone();
146        if n > 0 {
147            format!("{}.{}", f, n)
148        } else {
149            f
150        }
151    }
152
153    /// Rotates old files to make room for a new one.
154    /// This may result in the deletion of the oldest file
155    fn rotate_files(&mut self) -> io::Result<()> {
156        // ignore any failure removing the oldest file (may not exist)
157        let _ = fs::remove_file(self.filename_for(self.max_filecount.max(1)));
158        let mut r = Ok(());
159        for i in (0..self.max_filecount.max(1)).rev() {
160            let rotate_from = self.filename_for(i);
161            let rotate_to = self.filename_for(i + 1);
162            if let Err(e) = fs::rename(&rotate_from, &rotate_to).or_else(|e| match e.kind() {
163                io::ErrorKind::NotFound => Ok(()),
164                _ => Err(e),
165            }) {
166                // capture the error, but continue the loop,
167                // to maximize ability to rename everything
168                r = Err(e);
169            }
170        }
171        r
172    }
173
174    /// Forces a rollover to happen immediately.
175    pub fn rollover(&mut self) -> io::Result<()> {
176        // Before closing, make sure all data is flushed successfully.
177        self.flush()?;
178        // We must close the current file before rotating files
179        self.writer_opt.take();
180        self.current_filesize = 0;
181        self.rotate_files()?;
182        self.open_writer_if_needed()
183    }
184
185    /// Opens a writer for the current file.
186    fn open_writer_if_needed(&mut self) -> io::Result<()> {
187        if self.writer_opt.is_none() {
188            let path = self.filename_for(0);
189            let path = Path::new(&path);
190            let mut open_options = OpenOptions::new();
191            open_options.append(true).create(true);
192            let new_file = match open_options.open(path) {
193                Ok(new_file) => new_file,
194                Err(err) => {
195                    let Some(parent) = path.parent() else {
196                        return Err(err);
197                    };
198                    fs::create_dir_all(parent)?;
199                    open_options.open(path)?
200                },
201            };
202            self.writer_opt = Some(BufWriter::new(new_file));
203            self.current_filesize = path.metadata().map_or(0, |m| m.len());
204        }
205        Ok(())
206    }
207
208    /// Writes data using the given datetime to calculate the rolling condition
209    pub fn write_with_datetime(&mut self, buf: &[u8], now: &DateTime<Local>) -> io::Result<usize> {
210        if self.condition.should_rollover(now, self.current_filesize) {
211            if let Err(e) = self.rollover() {
212                // If we can't rollover, just try to continue writing anyway
213                // (better than missing data).
214                // This will likely used to implement logging, so
215                // avoid using log::warn and log to stderr directly
216                eprintln!("WARNING: Failed to rotate logfile {}: {}", self.filename, e);
217            }
218        }
219        self.open_writer_if_needed()?;
220        if let Some(writer) = self.writer_opt.as_mut() {
221            let buf_len = buf.len();
222            writer.write_all(buf).map(|_| {
223                self.current_filesize += u64::try_from(buf_len).unwrap_or(u64::MAX);
224                buf_len
225            })
226        } else {
227            Err(io::Error::other("unexpected condition: writer is missing"))
228        }
229    }
230}
231
232impl<RC> io::Write for RollingFileAppender<RC>
233where
234    RC: RollingCondition,
235{
236    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
237        let now = Local::now();
238        self.write_with_datetime(buf, &now)
239    }
240
241    fn flush(&mut self) -> io::Result<()> {
242        if let Some(writer) = self.writer_opt.as_mut() {
243            writer.flush()?;
244        }
245        Ok(())
246    }
247}
248
249pub mod base;
250pub use base::*;