Skip to main content

reth_tracing/
rolling.rs

1//! A log file writer that rotates by size.
2
3use std::{
4    ffi::OsString,
5    fs::{self, File, OpenOptions},
6    io::{self, BufWriter, Write},
7    path::PathBuf,
8};
9
10/// Writes to `path` and rotates it once it reaches `max_size_bytes`.
11///
12/// Rotation renames `path` to `path.1`, `path.1` to `path.2` and so on, keeping at most
13/// `max_files` rotated files. The size check runs before each write, so a file can exceed the
14/// limit by one write.
15#[derive(Debug)]
16pub(crate) struct RollingFileWriter {
17    path: PathBuf,
18    max_size_bytes: u64,
19    max_files: usize,
20    file_size: u64,
21    writer: Option<BufWriter<File>>,
22}
23
24impl RollingFileWriter {
25    /// Opens `path` for appending, creating it if needed.
26    pub(crate) fn new(path: PathBuf, max_size_bytes: u64, max_files: usize) -> io::Result<Self> {
27        let mut writer = Self { path, max_size_bytes, max_files, file_size: 0, writer: None };
28        writer.writer = Some(writer.open()?);
29        Ok(writer)
30    }
31
32    /// Returns the path of the rotated file with index `n`, or the active file for `0`.
33    fn rotated_path(&self, n: usize) -> PathBuf {
34        if n == 0 {
35            return self.path.clone()
36        }
37        let mut path = OsString::from(&self.path);
38        path.push(format!(".{n}"));
39        path.into()
40    }
41
42    /// Opens the active file for appending and records its current size.
43    fn open(&mut self) -> io::Result<BufWriter<File>> {
44        let file = OpenOptions::new().append(true).create(true).open(&self.path)?;
45        self.file_size = file.metadata()?.len();
46        Ok(BufWriter::new(file))
47    }
48
49    /// Closes the active file and shifts every file one index up, dropping the oldest.
50    fn rotate(&mut self) -> io::Result<()> {
51        if let Some(mut writer) = self.writer.take() {
52            writer.flush()?;
53        }
54        let last = self.max_files.max(1);
55        match fs::remove_file(self.rotated_path(last)) {
56            Err(err) if err.kind() != io::ErrorKind::NotFound => return Err(err),
57            _ => {}
58        }
59        for n in (0..last).rev() {
60            match fs::rename(self.rotated_path(n), self.rotated_path(n + 1)) {
61                Err(err) if err.kind() != io::ErrorKind::NotFound => return Err(err),
62                _ => {}
63            }
64        }
65        Ok(())
66    }
67}
68
69impl Write for RollingFileWriter {
70    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
71        if self.file_size >= self.max_size_bytes &&
72            let Err(err) = self.rotate()
73        {
74            // This writer backs the tracing subscriber, so the error can't be logged.
75            eprintln!("WARNING: Failed to rotate log file {}: {err}", self.path.display());
76        }
77        let writer = match self.writer.take() {
78            Some(writer) => writer,
79            None => self.open()?,
80        };
81        self.writer.insert(writer).write_all(buf)?;
82        self.file_size = self.file_size.saturating_add(buf.len() as u64);
83        Ok(buf.len())
84    }
85
86    fn flush(&mut self) -> io::Result<()> {
87        match self.writer.as_mut() {
88            Some(writer) => writer.flush(),
89            None => Ok(()),
90        }
91    }
92}
93
94#[cfg(test)]
95mod tests {
96    use super::*;
97    use std::path::Path;
98
99    fn read(path: &Path) -> String {
100        fs::read_to_string(path).unwrap()
101    }
102
103    #[test]
104    fn rotates_by_size_and_keeps_max_files() {
105        let dir = tempfile::tempdir().unwrap();
106        let path = dir.path().join("reth.log");
107        let mut writer = RollingFileWriter::new(path.clone(), 4, 2).unwrap();
108
109        for line in ["aaaa", "bbbb", "cccc", "dddd"] {
110            writer.write_all(line.as_bytes()).unwrap();
111        }
112        writer.flush().unwrap();
113
114        assert_eq!(read(&path), "dddd");
115        assert_eq!(read(&writer.rotated_path(1)), "cccc");
116        assert_eq!(read(&writer.rotated_path(2)), "bbbb");
117        assert!(!writer.rotated_path(3).exists());
118    }
119
120    #[test]
121    fn appends_to_existing_file() {
122        let dir = tempfile::tempdir().unwrap();
123        let path = dir.path().join("reth.log");
124        fs::write(&path, "abc").unwrap();
125
126        let mut writer = RollingFileWriter::new(path.clone(), 4, 1).unwrap();
127        writer.write_all(b"d").unwrap();
128        writer.write_all(b"e").unwrap();
129        writer.flush().unwrap();
130
131        assert_eq!(read(&writer.rotated_path(1)), "abcd");
132        assert_eq!(read(&path), "e");
133    }
134}