-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlog.rs
More file actions
166 lines (151 loc) · 4.3 KB
/
Copy pathlog.rs
File metadata and controls
166 lines (151 loc) · 4.3 KB
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
155
156
157
158
159
160
161
162
163
164
165
166
use crate::io;
use std::{
fmt::Display,
fs::{self, File},
io::Seek,
path::PathBuf,
time::{SystemTime, UNIX_EPOCH},
};
static MAX_LINES: u32 = 10_000;
#[derive(Debug, Clone, PartialEq, Default)]
pub enum Level {
#[default]
All,
Trace,
Warning,
Error,
Info,
Silent,
}
pub struct SimLogger<'a> {
level: Level,
output: Box<dyn std::io::Write + Sync + Send + 'a>,
}
pub struct LogFile {
currnet_line: u32,
current_chunk: u32,
name: String,
path: Option<String>,
file: File,
}
impl From<u32> for Level {
fn from(value: u32) -> Self {
match value {
0 => Level::All,
1 => Level::Trace,
2 => Level::Warning,
3 => Level::Error,
4 => Level::Info,
_ => Level::Silent,
}
}
}
impl<'a> SimLogger<'a> {
pub fn new(level: Level, output: impl std::io::Write + Sync + Send + 'static) -> Self {
Self {
level,
output: Box::new(output),
}
}
pub fn log(&mut self, level: Level, message: &str) {
if self.level.clone() as u32 <= level as u32 {
writeln!(self.output, "{message}").unwrap();
}
}
pub fn info(&mut self, message: &str) {
self.log(Level::Info, message)
}
pub fn error(&mut self, message: &str) {
self.log(Level::Error, message)
}
pub fn warning(&mut self, message: &str) {
self.log(Level::Warning, message)
}
pub fn trace(&mut self, message: &str) {
self.log(Level::Trace, message)
}
pub fn set_level(&mut self, level: Level) {
self.level = level
}
pub fn set_output(&mut self, output: impl std::io::Write + Sync + Send + 'a) {
self.output = Box::new(output)
}
}
impl LogFile {
pub fn new() -> Self {
let created = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as u64;
let name = format! {"simhttp-{created}"};
let mut path = PathBuf::from(".");
path.push(name.clone());
path.set_extension("log");
let file = File::create(path).expect("can't create log");
LogFile {
currnet_line: 0,
current_chunk: 0,
path: None,
name,
file,
}
}
pub fn from(path: impl Into<String>, name: &impl AsRef<str>, bind: &str, port: &f64) -> Self {
let created = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as u64;
let name: String = name.as_ref().to_string();
let name = simweb::interpolate(
&name,
&vec![
Box::new(&created as &dyn Display),
Box::new(&bind as &dyn Display),
Box::new(port as &dyn Display),
],
);
let path: String = path.into();
let mut log_path = PathBuf::from(&path);
log_path.push(format!("{name}.log"));
let file = File::create(&log_path)
.unwrap_or_else(|e| panic!("can't create log {log_path:?}/{e:?}"));
LogFile {
currnet_line: 0,
current_chunk: 0,
path: Some(path),
name,
file,
}
}
pub fn roll(&mut self) {
self.current_chunk += 1;
let mut path = match &self.path {
None => PathBuf::from("."),
Some(path) => PathBuf::from(path),
};
path.push(format!("{}.log", self.name));
let mut copy_path = path.clone();
copy_path.set_extension(format! {"log.{:05}", self.current_chunk});
if fs::copy(path, copy_path).is_ok() && self.file.rewind().is_ok() {
let _ = self.file.set_len(0);
}
}
}
impl std::io::Write for LogFile {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.file.write_all(buf)?;
if buf[buf.len() - 1] == b'\n' {
// add count of all \n in the string
self.currnet_line += 1;
if self.currnet_line > MAX_LINES {
self.roll();
self.currnet_line = 0;
}
}
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
// In this simple example, flush does nothing.
Ok(())
}
}