111 lines
3.8 KiB
Rust
111 lines
3.8 KiB
Rust
//! Log file: rotated by size, every line redacted.
|
|
|
|
use crate::redact;
|
|
use log::{Level, LevelFilter, Log, Metadata, Record};
|
|
use std::fs::{File, OpenOptions};
|
|
use std::io::{self, Write};
|
|
use std::os::unix::fs::OpenOptionsExt;
|
|
use std::path::{Path, PathBuf};
|
|
use std::sync::Mutex;
|
|
|
|
const MAX_BYTES: u64 = 1024 * 1024;
|
|
/// Old files kept beside the current one: `medlar.log.1`, `.2`, `.3`.
|
|
const KEEP: u32 = 3;
|
|
|
|
struct Rotating {
|
|
path: PathBuf,
|
|
max: u64,
|
|
file: File,
|
|
size: u64,
|
|
}
|
|
|
|
impl Rotating {
|
|
fn open(path: &Path, max: u64) -> io::Result<Rotating> {
|
|
let file = OpenOptions::new().create(true).append(true).mode(0o600).open(path)?;
|
|
let size = file.metadata()?.len();
|
|
Ok(Rotating { path: path.into(), max, file, size })
|
|
}
|
|
|
|
fn write(&mut self, line: &str) -> io::Result<()> {
|
|
if self.size > 0 && self.size + line.len() as u64 > self.max {
|
|
let old = |n: u32| PathBuf::from(format!("{}.{n}", self.path.display()));
|
|
for n in (1..KEEP).rev() {
|
|
let _ = std::fs::rename(old(n), old(n + 1));
|
|
}
|
|
std::fs::rename(&self.path, old(1))?;
|
|
*self = Rotating::open(&self.path, self.max)?;
|
|
}
|
|
self.size += line.len() as u64;
|
|
self.file.write_all(line.as_bytes())
|
|
}
|
|
}
|
|
|
|
struct Logger(Mutex<Rotating>);
|
|
|
|
impl Log for Logger {
|
|
fn enabled(&self, m: &Metadata) -> bool {
|
|
// Libraries speak up only when something is wrong.
|
|
m.level() <= Level::Warn || m.target().starts_with("medlar")
|
|
}
|
|
|
|
fn log(&self, r: &Record) {
|
|
if self.enabled(r.metadata()) {
|
|
let line = line(r.level(), r.target(), &r.args().to_string());
|
|
// A log that can't be written must not stop the app.
|
|
let _ = self.0.lock().unwrap_or_else(|e| e.into_inner()).write(&line);
|
|
}
|
|
}
|
|
|
|
fn flush(&self) {}
|
|
}
|
|
|
|
/// One entry is one line, whatever a server put into the message.
|
|
fn line(level: Level, target: &str, message: &str) -> String {
|
|
let message = redact::text(message).replace(|c: char| c.is_control(), " ");
|
|
format!("{} {level:5} {target}: {message}\n", chrono::Local::now().format("%Y-%m-%d %H:%M:%S%.3f"))
|
|
}
|
|
|
|
/// Starts logging to `path`. Call once; a second call changes nothing.
|
|
pub fn init(path: &Path, level: LevelFilter) -> io::Result<()> {
|
|
let logger = Logger(Mutex::new(Rotating::open(path, MAX_BYTES)?));
|
|
if log::set_boxed_logger(Box::new(logger)).is_ok() {
|
|
log::set_max_level(level);
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn rotates_and_keeps_three() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let path = dir.path().join("medlar.log");
|
|
let mut log = Rotating::open(&path, 25).unwrap();
|
|
for n in 0..12 {
|
|
log.write(&format!("line {n:04}\n")).unwrap();
|
|
}
|
|
assert_eq!(std::fs::read_to_string(&path).unwrap(), "line 0010\nline 0011\n");
|
|
assert_eq!(std::fs::read_to_string(dir.path().join("medlar.log.1")).unwrap(), "line 0008\nline 0009\n");
|
|
assert!(dir.path().join("medlar.log.3").exists());
|
|
assert!(!dir.path().join("medlar.log.4").exists());
|
|
assert!(std::fs::metadata(&path).unwrap().len() <= 25);
|
|
}
|
|
|
|
#[test]
|
|
fn continues_an_existing_file() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let path = dir.path().join("medlar.log");
|
|
Rotating::open(&path, 25).unwrap().write("first\n").unwrap();
|
|
Rotating::open(&path, 25).unwrap().write("second\n").unwrap();
|
|
assert_eq!(std::fs::read_to_string(&path).unwrap(), "first\nsecond\n");
|
|
}
|
|
|
|
#[test]
|
|
fn entries_are_one_redacted_line() {
|
|
let l = line(Level::Info, "medlar_core", "name evil\n2026 ERROR fake https://h/f?key=abc");
|
|
assert_eq!(l.matches('\n').count(), 1);
|
|
assert!(l.ends_with("name evil 2026 ERROR fake https://h/f?…\n"), "{l}");
|
|
}
|
|
}
|