Files
ianitor/crates/edge/src/logging.rs
T

172 lines
4.8 KiB
Rust

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Error log (stderr, always on; journald under systemd) and the per-host access log
//! (JSON lines in a local file, client IP truncated to /24 or /48, no query strings).
//!
//! Library crates (Pingora, rustls, h2, ...) are capped at `info` whatever `IANITOR_LOG` says:
//! their debug output can include raw request and response headers.
use std::fs::{File, OpenOptions};
use std::io::Write;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::path::Path;
use std::sync::Mutex;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use log::{Level, LevelFilter, Log, Metadata, Record};
use serde::Serialize;
use crate::error::EdgeError;
struct StderrLogger {
own: LevelFilter,
}
const LIBRARY_MAX: LevelFilter = LevelFilter::Info;
impl Log for StderrLogger {
fn enabled(&self, m: &Metadata<'_>) -> bool {
let limit = if m.target().starts_with("ianitor") {
self.own
} else {
self.own.min(LIBRARY_MAX)
};
m.level() <= limit
}
fn log(&self, r: &Record<'_>) {
if self.enabled(r.metadata()) {
let lvl = match r.level() {
Level::Error => "ERROR",
Level::Warn => "WARN",
Level::Info => "INFO",
Level::Debug => "DEBUG",
Level::Trace => "TRACE",
};
let mut err = std::io::stderr().lock();
let _ = writeln!(err, "{lvl} {}: {}", r.target(), r.args());
}
}
fn flush(&self) {
let _ = std::io::stderr().flush();
}
}
/// Install the stderr logger. `level` is `error`, `warn`, `info` (default), `debug` or `trace`.
pub fn init(level: Option<&str>) {
let own = match level.map(str::to_ascii_lowercase).as_deref() {
Some("error") => LevelFilter::Error,
Some("warn") => LevelFilter::Warn,
Some("debug") => LevelFilter::Debug,
Some("trace") => LevelFilter::Trace,
_ => LevelFilter::Info,
};
if log::set_boxed_logger(Box::new(StderrLogger { own })).is_ok() {
log::set_max_level(own);
}
}
/// IPv4 → /24, IPv6 → /48 (IPv4-mapped IPv6 is treated as IPv4).
pub fn truncate_ip(ip: IpAddr) -> IpAddr {
match ip {
IpAddr::V4(v4) => {
let [a, b, c, _] = v4.octets();
IpAddr::V4(Ipv4Addr::new(a, b, c, 0))
}
IpAddr::V6(v6) => match v6.to_ipv4_mapped() {
Some(v4) => truncate_ip(IpAddr::V4(v4)),
None => {
let s = v6.segments();
IpAddr::V6(Ipv6Addr::new(s[0], s[1], s[2], 0, 0, 0, 0, 0))
}
},
}
}
#[derive(Serialize)]
pub struct AccessRecord<'a> {
pub ts: f64,
pub host: &'a str,
pub method: &'a str,
/// Path only: query strings can carry tokens.
pub path: &'a str,
pub status: u16,
pub remote_ip: Option<String>,
pub duration_ms: u64,
}
pub fn now_secs() -> f64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or(Duration::ZERO)
.as_secs_f64()
}
pub struct AccessLog {
file: Mutex<File>,
}
impl AccessLog {
pub fn open(path: &Path) -> Result<AccessLog, EdgeError> {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir).map_err(|source| EdgeError::Write {
path: dir.to_owned(),
source,
})?;
}
let mut opts = OpenOptions::new();
opts.create(true).append(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::mode(&mut opts, 0o640);
let file = opts.open(path).map_err(|source| EdgeError::Write {
path: path.to_owned(),
source,
})?;
Ok(AccessLog {
file: Mutex::new(file),
})
}
pub fn write(&self, rec: &AccessRecord<'_>) {
let Ok(mut line) = serde_json::to_vec(rec) else {
return;
};
line.push(b'\n');
if let Ok(mut f) = self.file.lock()
&& let Err(e) = f.write_all(&line)
{
log::error!(target: "ianitor::access", "cannot write the access log: {e}");
}
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
fn t(s: &str) -> String {
truncate_ip(s.parse().unwrap()).to_string()
}
#[test]
fn ipv4_is_truncated_to_24() {
assert_eq!(t("192.168.17.42"), "192.168.17.0");
assert_eq!(t("127.0.0.1"), "127.0.0.0");
}
#[test]
fn ipv6_is_truncated_to_48() {
assert_eq!(t("2001:db8:abcd:12:3456::1"), "2001:db8:abcd::");
assert_eq!(t("::1"), "::");
}
#[test]
fn mapped_ipv4_is_treated_as_ipv4() {
assert_eq!(t("::ffff:10.1.2.3"), "10.1.2.0");
}
}