1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
#![warn(
missing_docs,
missing_debug_implementations,
missing_copy_implementations
)]
use std::borrow::Cow;
use std::fs;
use std::io::{self, prelude::*};
use std::path::{Path, PathBuf};
use std::time::Duration;
#[derive(Clone, Copy, Debug, Ord, PartialOrd, Eq, PartialEq)]
#[non_exhaustive]
pub enum RotationPeriod {
Lines(usize),
Bytes(usize),
Interval(Duration),
}
mod rotation_tracker;
use rotation_tracker::RotationTracker;
#[derive(Debug)]
pub struct RotatingFile {
name: Cow<'static, str>,
directory: PathBuf,
rotation_tracker: RotationTracker,
max_files: usize,
current_file: Option<fs::File>,
}
impl RotatingFile {
pub fn new<Name, Directory>(
name: Name,
directory: Directory,
rotate_every: RotationPeriod,
max_files: usize,
) -> Self
where
Name: Into<Cow<'static, str>>,
Directory: Into<PathBuf>,
{
Self {
name: name.into(),
directory: directory.into(),
rotation_tracker: RotationTracker::from(rotate_every),
max_files,
current_file: None,
}
}
fn should_rotate(&self) -> bool {
self.current_file.is_none() || self.rotation_tracker.should_rotate()
}
fn logfile_index<P: AsRef<Path>>(&self, path: P) -> Option<usize> {
let path = path.as_ref();
let filename = path.file_stem()?.to_str()?;
let extension = path.extension()?;
if filename.starts_with(self.name.as_ref()) && extension == "log" {
filename[self.name.len() + '.'.len_utf8()..].parse().ok()
} else {
None
}
}
fn increment_index(&self, index: usize, path: PathBuf) -> io::Result<()> {
debug_assert_eq!(self.logfile_index(&path), Some(index));
fs::rename(path, self.make_filepath(index + 1))
}
fn make_filepath(&self, index: usize) -> PathBuf {
self.directory.join(format!("{}.{}.log", self.name, index))
}
fn create_file(&self) -> io::Result<fs::File> {
let max_index = itertools::process_results(fs::read_dir(&self.directory)?, |dir| {
dir.into_iter()
.filter_map(|entry| self.logfile_index(entry.path()))
.max()
})?;
if let Some(max_index) = max_index {
(0..max_index + if max_index >= self.max_files { 0 } else { 1 })
.rev()
.try_for_each(|index| self.increment_index(index, self.make_filepath(index)))?;
}
fs::OpenOptions::new()
.create_new(true)
.write(true)
.open(self.make_filepath(0))
}
fn current_file(&mut self) -> io::Result<&mut fs::File> {
if self.should_rotate() {
self.current_file = Some(self.create_file()?);
self.rotation_tracker.reset();
}
Ok(self
.current_file
.as_mut()
.expect("should've been created before"))
}
}
impl Write for RotatingFile {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
let file = self.current_file()?;
let written = file.write(buf)?;
self.rotation_tracker.wrote(&buf[..written]);
Ok(written)
}
fn flush(&mut self) -> std::io::Result<()> {
self.current_file()?.flush()
}
}