This commit is contained in:
Mateusz Gruszczyński committed 2026-11-23 23:03:30 +01:00
1 parent 96eec3b1c6
commit b9a5b3c153
30 files changed
+1100 -374

No files matched your search

+74 -15
View File
@@ -21,6 +21,42 @@ struct FileLogSource {
size: u64,
modified_ms: u64,
compressed: bool,
/// 0 = file being written; N = rotation `.N` / `.N.gz` (higher is older).
rotation: u32,
/// vhost, redirect, host404, unmatched, access or error.
scope: &'static str,
/// Site id for per-site logs (vhost, redirect or 404 host id).
site: String,
}
/// Splits `<base>.jsonl[.<N>][.gz]` (or `<file>[.<N>][.gz]` for the global logs)
/// into the rotation index; `None` for files that are not part of the set.
fn rotation_suffix(rest: &str) -> Option<(u32, bool)> {
if rest.is_empty() {
return Some((0, false));
}
let rest = rest.strip_prefix('.')?;
let (number, compressed) = match rest.strip_suffix(".gz") {
Some(number) => (number, true),
None => (rest, false),
};
if !number.is_empty() && number.len() <= 6 && number.bytes().all(|b| b.is_ascii_digit()) {
return number.parse().ok().map(|n: u32| (n.max(1), compressed));
}
// Other compressed rotations (e.g. `.old.gz`) sort after numbered ones.
compressed.then_some((u32::MAX, true))
}
/// Scope and site of a per-site log base name (`app`, `old.redirect`, `park.host404`).
fn site_scope(base: &str) -> (&'static str, String) {
if base == "_unmatched" {
return ("unmatched", String::new());
}
if let Some(id) = base.strip_suffix(".redirect") {
return ("redirect", id.to_owned());
}
if let Some(id) = base.strip_suffix(".host404") {
return ("host404", id.to_owned());
}
("vhost", base.to_owned())
}
#[derive(Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
@@ -32,6 +68,8 @@ struct FileLogQuery {
client_ip: Option<String>,
vhost: Option<String>,
consolidate_vhosts: Option<bool>,
/// Only records at or after this time (ms since the epoch).
since_ms: Option<u64>,
aggregate_field: Option<String>,
aggregate_limit: Option<usize>,
aggregate_min_count: Option<usize>,
@@ -83,6 +121,9 @@ fn source_from_path(
.filter(|_| safe_regular)
.map_or(0, file_modified_ms),
compressed,
rotation: 0,
scope: kind,
site: String::new(),
}
}
include!("file_logs_io.rs");
@@ -103,11 +144,11 @@ fn configured_file_log_sources(config: &crate::config::Config) -> Vec<FileLogSou
.filter_map(|entry| {
let path = entry.path();
let name = entry.file_name().to_string_lossy().into_owned();
let plain = name.ends_with(".jsonl");
let rotated = name.contains(".jsonl.") && name.ends_with(".gz");
if (!plain && !rotated) || name.len() > 180 {
let (base, rest) = name.split_once(".jsonl")?;
if base.is_empty() || name.len() > 180 {
return None;
}
rotation_suffix(rest)?;
let file_type = entry.file_type().ok()?;
if !file_type.is_file() || file_type.is_symlink() {
return None;
@@ -118,25 +159,40 @@ fn configured_file_log_sources(config: &crate::config::Config) -> Vec<FileLogSou
256,
);
for (name, path, _) in entries {
let id = if name.ends_with(".jsonl") {
format!("vhost:{}", name.trim_end_matches(".jsonl"))
} else {
format!("vhost-gz:{name}")
let Some((base, rest)) = name.split_once(".jsonl") else {
continue;
};
let vhost_name = name
.split_once(".jsonl")
.map_or(name.as_str(), |(prefix, _)| prefix);
let group_id = format!("vhost:{vhost_name}");
sources.push(source_from_path(
let Some((rotation, compressed)) = rotation_suffix(rest) else {
continue;
};
let id = if rotation == 0 {
format!("vhost:{base}")
} else if compressed {
format!("vhost-gz:{name}")
} else {
format!("vhost-file:{name}")
};
let (scope, site) = site_scope(base);
let mut source = source_from_path(
id,
name,
group_id,
name.clone(),
format!("vhost:{base}"),
"access",
path,
config.logging.file.enabled,
"JSONL",
));
);
source.rotation = rotation;
source.scope = scope;
source.site = site;
sources.push(source);
}
sources.sort_by(|a, b| {
a.group_id
.cmp(&b.group_id)
.then_with(|| a.rotation.cmp(&b.rotation))
.then_with(|| b.modified_ms.cmp(&a.modified_ms))
});
}
} else {
let access_path = std::path::PathBuf::from(&config.logging.file.path);
@@ -199,6 +255,9 @@ fn file_log_sources_json(sources: &[FileLogSource]) -> Value {
"size": source.size,
"modified_ms": source.modified_ms,
"compressed": source.compressed,
"rotation": source.rotation,
"scope": source.scope,
"site": source.site,
})
})
.collect(),
+28 -8
View File
@@ -24,6 +24,8 @@ fn newest_log_files(
result
}
/// Rotated copies of a global log: `<file>.N`, `<file>.N.gz` (logrotate with or
/// without `delaycompress`) and other `<file>.*.gz`, newest rotation first.
fn rotated_gzip_sources(
active: &std::path::Path,
id_prefix: &str,
@@ -44,7 +46,6 @@ fn rotated_gzip_sources(
if !safe {
return Vec::new();
}
let prefix = format!("{base}.");
let entries = newest_log_files(
std::fs::read_dir(parent)
.ok()
@@ -52,7 +53,8 @@ fn rotated_gzip_sources(
.flat_map(|iter| iter.filter_map(|entry| entry.ok()))
.filter_map(|entry| {
let name = entry.file_name().to_string_lossy().into_owned();
if name.len() > 180 || !name.starts_with(&prefix) || !name.ends_with(".gz") {
let rest = name.strip_prefix(base)?;
if name.len() > 180 || rest.is_empty() || rotation_suffix(rest).is_none() {
return None;
}
let file_type = entry.file_type().ok()?;
@@ -64,20 +66,38 @@ fn rotated_gzip_sources(
}),
64,
);
entries
let mut sources: Vec<FileLogSource> = entries
.into_iter()
.map(|(name, path, _)| {
source_from_path(
format!("{id_prefix}:gz:{name}"),
.filter_map(|(name, path, _)| {
let (rotation, compressed) = rotation_suffix(&name[base.len()..])?;
let mut source = source_from_path(
if compressed {
format!("{id_prefix}:gz:{name}")
} else {
format!("{id_prefix}:file:{name}")
},
format!("{label_prefix} · {name}"),
id_prefix.to_owned(),
kind,
path,
enabled,
format,
)
);
source.rotation = rotation;
Some(source)
})
.collect()
.collect();
sort_by_rotation(&mut sources);
sources
}
/// Newest data first: the file being written, then `.1`, `.2`, … (ties by mtime).
fn sort_by_rotation(sources: &mut [FileLogSource]) {
sources.sort_by(|a, b| {
a.rotation
.cmp(&b.rotation)
.then_with(|| b.modified_ms.cmp(&a.modified_ms))
.then_with(|| a.id.cmp(&b.id))
});
}
fn open_file_log(path: &std::path::Path) -> std::io::Result<std::fs::File> {
+192 -138
View File
@@ -208,6 +208,197 @@ fn validate_file_log_query(query: &FileLogQuery) -> Result<(), ApiError> {
Ok(())
}
/// Runs a stored-log query (blocking file I/O).
fn file_log_query_blocking(
config: &crate::config::Config,
query: &FileLogQuery,
search: &[FileLogSearchClause],
) -> Result<Json<Value>, ApiError> {
let mut sources = configured_file_log_sources(config);
let log_format = config.logging.format.clone();
let requested = query.source.as_deref().unwrap_or("all");
let mut truncated = false;
let mut files_skipped = 0usize;
// One site/log (all its rotations) or one file is read newest-first: each file
// may use the whole remaining budget, so the newest records are always
// complete and older rotations are read only while budget remains. "All"
// spreads the budget over the newest file of every log first.
let sequential = requested != "all";
if requested != "all" {
let consolidate = query.consolidate_vhosts.unwrap_or(false);
sources.retain(|source| {
source.id == requested || (consolidate && source.group_id == requested)
});
if sources.is_empty() {
return Err(ApiError(
StatusCode::BAD_REQUEST,
"unknown file log source".into(),
));
}
sort_by_rotation(&mut sources);
} else {
sort_by_rotation(&mut sources);
}
if sources.len() > FILE_LOG_MAX_SOURCES {
truncated = true;
files_skipped += sources.len() - FILE_LOG_MAX_SOURCES;
sources.truncate(FILE_LOG_MAX_SOURCES);
}
let since_ms = query.since_ms.filter(|value| *value > 0);
let mut files = Vec::new();
let mut newest_ms: Option<u64> = None;
let mut oldest_ms: Option<u64> = None;
let offset = query.offset.unwrap_or(0);
let limit = query.limit.unwrap_or(100).clamp(1, FILE_LOG_MAX_LIMIT);
let mut remaining_bytes = FILE_LOG_SCAN_BYTES_TOTAL;
let mut scanned_bytes = 0u64;
let mut remaining_lines = FILE_LOG_SCAN_LINES;
let mut scanned_lines = 0usize;
let mut records = Vec::new();
let mut fields = std::collections::BTreeSet::new();
let aggregate_field = query
.aggregate_field
.as_deref()
.map(str::to_ascii_lowercase);
let aggregate_min_count = query.aggregate_min_count.unwrap_or(2);
let aggregate_limit = query
.aggregate_limit
.unwrap_or(50)
.clamp(1, FILE_LOG_MAX_AGGREGATE_RESULTS);
let mut aggregate_counts = std::collections::HashMap::<String, usize>::new();
let mut aggregate_truncated = false;
let mut reached_since = false;
for (index, source) in sources.iter().enumerate() {
if remaining_bytes == 0 || remaining_lines == 0 || reached_since {
truncated |= !reached_since;
files_skipped += sources.len() - index;
break;
}
let sources_left = sources.len().saturating_sub(index).max(1);
let line_budget = if sequential {
remaining_lines
} else {
(remaining_lines / sources_left).max(1)
};
match read_tail(source, remaining_bytes, line_budget) {
Ok((lines, bytes, source_truncated)) => {
remaining_bytes = remaining_bytes.saturating_sub(bytes);
remaining_lines = remaining_lines.saturating_sub(lines.len());
scanned_bytes += bytes;
scanned_lines += lines.len();
truncated |= source_truncated;
files.push(json!({
"id": source.id,
"rotation": source.rotation,
"lines": lines.len(),
"partial": source_truncated,
}));
let mut file_newest: Option<u64> = None;
for line in lines {
if line.is_empty() {
continue;
}
let value = normalized_record(source, &line, &log_format);
let time = value.get("time_ms").and_then(Value::as_u64);
if let Some(time) = time {
file_newest = Some(file_newest.map_or(time, |n: u64| n.max(time)));
}
if since_ms.is_some_and(|since| time.is_some_and(|time| time < since)) {
continue;
}
if record_matches(&value, query, search) {
if let Some(time) = time {
newest_ms = Some(newest_ms.map_or(time, |n| n.max(time)));
oldest_ms = Some(oldest_ms.map_or(time, |o| o.min(time)));
}
collect_file_log_fields(&value, &mut fields);
if let Some(field) = aggregate_field.as_deref() {
if let Some(field_value) = file_log_field(&value, field) {
let mut values = Vec::new();
file_log_aggregate_values(field_value, &mut values);
for aggregate_value in values {
if aggregate_counts.contains_key(&aggregate_value)
|| aggregate_counts.len()
< FILE_LOG_MAX_AGGREGATE_VALUES
{
*aggregate_counts
.entry(aggregate_value)
.or_insert(0) += 1;
} else {
aggregate_truncated = true;
}
}
}
}
records.push(value);
}
}
// Older rotations only hold older records: stop once a whole file
// is before the requested period.
if sequential
&& since_ms.is_some_and(|since| file_newest.is_some_and(|n| n < since))
{
reached_since = true;
}
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(_) => truncated = true,
}
}
sort_file_log_records(
&mut records,
query.sort_by.as_deref().unwrap_or("time"),
query.sort_descending.unwrap_or(true),
);
let mut aggregation = aggregate_counts
.into_iter()
.filter(|(_, count)| *count >= aggregate_min_count)
.map(|(value, count)| json!({"value": value, "count": count}))
.collect::<Vec<_>>();
aggregation.sort_by(|left, right| {
let left_count = left.get("count").and_then(Value::as_u64).unwrap_or(0);
let right_count = right.get("count").and_then(Value::as_u64).unwrap_or(0);
right_count.cmp(&left_count).then_with(|| {
left.get("value")
.and_then(Value::as_str)
.unwrap_or("")
.cmp(right.get("value").and_then(Value::as_str).unwrap_or(""))
})
});
if aggregation.len() > aggregate_limit {
aggregation.truncate(aggregate_limit);
aggregate_truncated = true;
}
let total = records.len();
let page = records
.into_iter()
.skip(offset)
.take(limit)
.collect::<Vec<_>>();
Ok(Json(json!({
"entries": page,
"total": total,
"offset": offset,
"limit": limit,
"truncated": truncated,
"scanned_bytes": scanned_bytes,
"scanned_lines": scanned_lines,
"files": files,
"files_skipped": files_skipped,
"stopped_at_period": reached_since,
"newest_ms": newest_ms,
"oldest_ms": oldest_ms,
"fields": fields,
"sources": file_log_sources_json(&sources),
"aggregation": aggregate_field.map(|field| json!({
"field": field,
"min_count": aggregate_min_count,
"entries": aggregation,
"truncated": aggregate_truncated,
})),
})))
}
async fn file_logs_query(
State(state): State<Arc<App>>,
Query(query): Query<FileLogQuery>,
@@ -215,144 +406,7 @@ async fn file_logs_query(
validate_file_log_query(&query)?;
let search = parse_file_log_search(query.q.as_deref().unwrap_or(""))?;
let config = state.config.load().envelope.config.clone();
tokio::task::spawn_blocking(move || {
let mut sources = configured_file_log_sources(&config);
let log_format = config.logging.format.clone();
let requested = query.source.as_deref().unwrap_or("all");
let mut truncated = false;
if requested != "all" {
let consolidate_vhosts =
query.consolidate_vhosts.unwrap_or(false) && requested.starts_with("vhost:");
sources.retain(|source| {
source.id == requested || (consolidate_vhosts && source.group_id == requested)
});
if sources.is_empty() {
return Err(ApiError(
StatusCode::BAD_REQUEST,
"unknown file log source".into(),
));
}
} else {
sources.sort_by_key(|source| std::cmp::Reverse(source.modified_ms));
if sources.len() > FILE_LOG_MAX_SOURCES {
truncated = true;
sources.truncate(FILE_LOG_MAX_SOURCES);
}
}
let offset = query.offset.unwrap_or(0);
let limit = query.limit.unwrap_or(100).clamp(1, FILE_LOG_MAX_LIMIT);
let mut remaining_bytes = FILE_LOG_SCAN_BYTES_TOTAL;
let mut scanned_bytes = 0u64;
let mut remaining_lines = FILE_LOG_SCAN_LINES;
let mut scanned_lines = 0usize;
let mut records = Vec::new();
let mut fields = std::collections::BTreeSet::new();
let aggregate_field = query
.aggregate_field
.as_deref()
.map(str::to_ascii_lowercase);
let aggregate_min_count = query.aggregate_min_count.unwrap_or(2);
let aggregate_limit = query
.aggregate_limit
.unwrap_or(50)
.clamp(1, FILE_LOG_MAX_AGGREGATE_RESULTS);
let mut aggregate_counts = std::collections::HashMap::<String, usize>::new();
let mut aggregate_truncated = false;
for (index, source) in sources.iter().enumerate() {
if remaining_bytes == 0 || remaining_lines == 0 {
truncated = true;
break;
}
let sources_left = sources.len().saturating_sub(index).max(1);
let line_budget = (remaining_lines / sources_left).max(1);
match read_tail(source, remaining_bytes, line_budget) {
Ok((lines, bytes, source_truncated)) => {
remaining_bytes = remaining_bytes.saturating_sub(bytes);
remaining_lines = remaining_lines.saturating_sub(lines.len());
scanned_bytes += bytes;
scanned_lines += lines.len();
truncated |= source_truncated;
for line in lines {
if line.is_empty() {
continue;
}
let value = normalized_record(source, &line, &log_format);
if record_matches(&value, &query, &search) {
collect_file_log_fields(&value, &mut fields);
if let Some(field) = aggregate_field.as_deref() {
if let Some(field_value) = file_log_field(&value, field) {
let mut values = Vec::new();
file_log_aggregate_values(field_value, &mut values);
for aggregate_value in values {
if aggregate_counts.contains_key(&aggregate_value)
|| aggregate_counts.len()
< FILE_LOG_MAX_AGGREGATE_VALUES
{
*aggregate_counts
.entry(aggregate_value)
.or_insert(0) += 1;
} else {
aggregate_truncated = true;
}
}
}
}
records.push(value);
}
}
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(_) => truncated = true,
}
}
sort_file_log_records(
&mut records,
query.sort_by.as_deref().unwrap_or("time"),
query.sort_descending.unwrap_or(true),
);
let mut aggregation = aggregate_counts
.into_iter()
.filter(|(_, count)| *count >= aggregate_min_count)
.map(|(value, count)| json!({"value": value, "count": count}))
.collect::<Vec<_>>();
aggregation.sort_by(|left, right| {
let left_count = left.get("count").and_then(Value::as_u64).unwrap_or(0);
let right_count = right.get("count").and_then(Value::as_u64).unwrap_or(0);
right_count.cmp(&left_count).then_with(|| {
left.get("value")
.and_then(Value::as_str)
.unwrap_or("")
.cmp(right.get("value").and_then(Value::as_str).unwrap_or(""))
})
});
if aggregation.len() > aggregate_limit {
aggregation.truncate(aggregate_limit);
aggregate_truncated = true;
}
let total = records.len();
let page = records
.into_iter()
.skip(offset)
.take(limit)
.collect::<Vec<_>>();
Ok(Json(json!({
"entries": page,
"total": total,
"offset": offset,
"limit": limit,
"truncated": truncated,
"scanned_bytes": scanned_bytes,
"scanned_lines": scanned_lines,
"fields": fields,
"sources": file_log_sources_json(&sources),
"aggregation": aggregate_field.map(|field| json!({
"field": field,
"min_count": aggregate_min_count,
"entries": aggregation,
"truncated": aggregate_truncated,
})),
})))
})
tokio::task::spawn_blocking(move || file_log_query_blocking(&config, &query, &search))
.await
.map_err(|_| {
ApiError(
+14 -4
View File
@@ -14809,7 +14809,7 @@
"/api/file-logs": {
"get": {
"summary": "Configured on-disk log sources",
"description": "Lists only RustProxy log paths from the active configuration. This endpoint is independent from the Live Logs memory buffer and does not accept a filesystem path.",
"description": "Lists only RustProxy log paths from the active configuration. This endpoint is independent from the Live Logs memory buffer and does not accept a filesystem path. Each source reports rotation (0 = file being written, N = .N/.N.gz), scope (vhost, redirect, host404, unmatched, access, error) and site (the vhost, redirect or 404 host id for per-site logs).",
"tags": [
"Monitoring"
],
@@ -14879,7 +14879,7 @@
"/api/file-logs/query": {
"get": {
"summary": "Query configured on-disk logs",
"description": "Reads bounded tails of configured RustProxy access/error log files using server-side source IDs only. The query never accepts arbitrary paths, follows no symlink on Unix, and is separate from /api/logs and /api/live-logs.",
"description": "Reads bounded tails of configured RustProxy access/error log files using server-side source IDs only. The query never accepts arbitrary paths, follows no symlink on Unix, and is separate from /api/logs and /api/live-logs. A log (group) is read newest rotation first; each file may use the remaining scan budget. The response adds files (id, rotation, lines, partial), files_skipped, stopped_at_period, newest_ms and oldest_ms.",
"tags": [
"Monitoring"
],
@@ -14889,7 +14889,7 @@
"name": "source",
"in": "query",
"required": false,
"description": "Source ID returned by /api/file-logs, or all. Never a filesystem path.",
"description": "Source or group ID returned by /api/file-logs, or all. Never a filesystem path. A single source (e.g. vhost-gz:app.jsonl.3.gz) reads only that file.",
"schema": {
"type": "string"
}
@@ -14898,12 +14898,22 @@
"name": "consolidate_vhosts",
"in": "query",
"required": false,
"description": "When true and source is vhost:<id>, scan the active JSONL plus all discovered rotated .gz members that share that vhost group.",
"description": "When true and source is a group ID (vhost:<base>, access or error), scan the current file and all rotations of that log (.N and .N.gz), newest rotation first.",
"schema": {
"type": "boolean",
"default": false
}
},
{
"name": "since_ms",
"in": "query",
"required": false,
"description": "Only records with time_ms at or after this value (ms since the Unix epoch). For a log read newest-first, reading stops at the first rotation that is entirely older.",
"schema": {
"type": "integer",
"minimum": 0
}
},
{
"name": "q",
"in": "query",
+144
View File
@@ -3219,6 +3219,150 @@ mod tests {
assert!(app.iter().any(|source| source.compressed));
}
fn write_gz(path: &std::path::Path, lines: &[String]) {
use std::io::Write;
let file = std::fs::File::create(path).unwrap();
let mut encoder = flate2::write::GzEncoder::new(file, flate2::Compression::default());
for line in lines {
writeln!(encoder, "{line}").unwrap();
}
encoder.finish().unwrap();
}
fn records(from: u64, to: u64) -> Vec<String> {
(from..to)
.map(|time| format!(r#"{{"event":"request","time_ms":{time},"status":200,"path":"/p{time}"}}"#))
.collect()
}
#[test]
fn stored_log_rotations_are_read_newest_first_regardless_of_mtime() {
let dir = tempfile::tempdir().unwrap();
// logrotate numbering: .jsonl newest, .1 (delaycompress, plain), .2.gz, .10.gz oldest.
std::fs::write(dir.path().join("mail.jsonl"), records(400, 410).join("\n") + "\n").unwrap();
std::fs::write(dir.path().join("mail.jsonl.1"), records(300, 310).join("\n") + "\n").unwrap();
write_gz(&dir.path().join("mail.jsonl.2.gz"), &records(200, 210));
write_gz(&dir.path().join("mail.jsonl.10.gz"), &records(100, 110));
// The oldest rotation has the newest mtime (copied or touched files).
std::fs::File::options()
.append(true)
.open(dir.path().join("mail.jsonl.10.gz"))
.unwrap()
.set_modified(std::time::SystemTime::now() + std::time::Duration::from_secs(3600))
.unwrap();
std::fs::write(dir.path().join("old.redirect.jsonl"), records(1, 2).join("\n")).unwrap();
std::fs::write(dir.path().join("park.host404.jsonl"), records(1, 2).join("\n")).unwrap();
std::fs::write(dir.path().join("_unmatched.jsonl"), records(1, 2).join("\n")).unwrap();
std::fs::write(dir.path().join("mail.jsonl-20261113.gz"), b"ignored").unwrap();
let mut config = Config::default();
config.logging.file.per_vhost = true;
config.logging.file.directory = dir.path().to_string_lossy().into_owned();
config.error_log.path = dir.path().join("none/error.log").to_string_lossy().into_owned();
let sources = configured_file_log_sources(&config);
let mail: Vec<_> = sources.iter().filter(|s| s.group_id == "vhost:mail").collect();
assert_eq!(
mail.iter().map(|s| (s.id.as_str(), s.rotation)).collect::<Vec<_>>(),
vec![
("vhost:mail", 0),
("vhost-file:mail.jsonl.1", 1),
("vhost-gz:mail.jsonl.2.gz", 2),
("vhost-gz:mail.jsonl.10.gz", 10)
]
);
let scope = |id: &str| sources.iter().find(|s| s.id == id).map(|s| (s.scope, s.site.clone()));
assert_eq!(scope("vhost:old.redirect"), Some(("redirect", "old".into())));
assert_eq!(scope("vhost:park.host404"), Some(("host404", "park".into())));
assert_eq!(scope("vhost:_unmatched"), Some(("unmatched", String::new())));
assert_eq!(scope("vhost:mail"), Some(("vhost", "mail".into())));
let query = |extra: FileLogQuery| {
let query = FileLogQuery {
source: Some("vhost:mail".into()),
consolidate_vhosts: Some(true),
limit: Some(5),
..extra
};
file_log_query_blocking(&config, &query, &[]).unwrap().0
};
let value = query(FileLogQuery::default());
let times: Vec<u64> = value["entries"]
.as_array()
.unwrap()
.iter()
.map(|e| e["time_ms"].as_u64().unwrap())
.collect();
assert_eq!(times, vec![409, 408, 407, 406, 405]);
assert_eq!(value["total"], 40);
assert_eq!(value["newest_ms"], 409);
assert_eq!(value["oldest_ms"], 100);
let files: Vec<_> = value["files"].as_array().unwrap().iter().map(|f| f["rotation"].as_u64().unwrap()).collect();
assert_eq!(files, vec![0, 1, 2, 10]);
// A period stops before older rotations.
let value = query(FileLogQuery {
since_ms: Some(305),
..FileLogQuery::default()
});
assert_eq!(value["total"], 15);
assert_eq!(value["oldest_ms"], 305);
// .2.gz is read to learn that it is entirely older; .10.gz is skipped.
assert_eq!(value["files"].as_array().unwrap().len(), 3);
assert_eq!(value["files_skipped"], 1);
// A single rotated file is its own source.
let value = file_log_query_blocking(
&config,
&FileLogQuery {
source: Some("vhost-gz:mail.jsonl.10.gz".into()),
..FileLogQuery::default()
},
&[],
)
.unwrap()
.0;
assert_eq!(value["newest_ms"], 109);
assert_eq!(value["total"], 10);
}
#[test]
fn stored_log_global_rotations_include_uncompressed_copies() {
let dir = tempfile::tempdir().unwrap();
let active = dir.path().join("access.jsonl");
std::fs::write(&active, records(30, 31).join("\n")).unwrap();
std::fs::write(dir.path().join("access.jsonl.1"), records(20, 21).join("\n")).unwrap();
write_gz(&dir.path().join("access.jsonl.2.gz"), &records(10, 11));
let mut config = Config::default();
config.logging.file.per_vhost = false;
config.logging.file.path = active.to_string_lossy().into_owned();
let sources = configured_file_log_sources(&config);
let access: Vec<_> = sources
.iter()
.filter(|s| s.group_id == "access")
.map(|s| (s.id.clone(), s.rotation))
.collect();
assert_eq!(
access,
vec![
("access".to_string(), 0),
("access:file:access.jsonl.1".to_string(), 1),
("access:gz:access.jsonl.2.gz".to_string(), 2)
]
);
let value = file_log_query_blocking(
&config,
&FileLogQuery {
source: Some("access".into()),
consolidate_vhosts: Some(true),
..FileLogQuery::default()
},
&[],
)
.unwrap()
.0;
assert_eq!(value["total"], 3);
assert_eq!(value["entries"][0]["time_ms"], 30);
}
#[test]
fn stored_log_aggregate_values_support_scalars_and_bounded_arrays() {
let value = json!(["BadBot/1", "BadBot/1", 503, true, {"ignored":"object"}]);
+3 -6
View File
@@ -204,8 +204,7 @@ button:focus-visible {
}
.quiet:hover,
.top-log-menu[open]>summary,
.file-log-search-help[open]>summary {
.top-log-menu[open]>summary {
color: var(--text);
border-color: var(--border-hover);
}
@@ -1348,8 +1347,7 @@ html[data-interface-icons="true"] .network-interface-hidden .quiet>svg.ui-icon {
.metric-info,
.top-log-menu,
.backend-column-picker,
.file-log-search-help {
.backend-column-picker {
position: relative;
}
@@ -1372,8 +1370,7 @@ html[data-interface-icons="true"] .network-interface-hidden .quiet>svg.ui-icon {
.top-log-menu>summary::-webkit-details-marker,
.function-live-chart-summary::-webkit-details-marker,
.backend-column-picker>summary::-webkit-details-marker,
.log-column-picker>summary::-webkit-details-marker,
.file-log-search-help>summary::-webkit-details-marker {
.log-column-picker>summary::-webkit-details-marker {
display: none;
}
+1 -2
View File
@@ -607,8 +607,7 @@ main {
}
.top-log-menu>summary,
.backend-column-picker>summary,
.file-log-search-help>summary {
.backend-column-picker>summary {
list-style: none;
cursor: pointer;
user-select: none;
+1 -2
View File
@@ -2108,8 +2108,7 @@ html:is([data-corner-style=square], [data-corner-style=subtle], [data-corner-sty
border-radius: var(--rp-progress-radius);
}
#panel-overview .stat-meter>small,
.file-log-search-help-popover code {
#panel-overview .stat-meter>small {
display: block;
overflow-wrap: anywhere;
}
-21
View File
@@ -597,7 +597,6 @@ p,
#panel-tls .certificate-subheading h3,
#panel-tls .certificate-library-footer p,
.cache-operation-dialog .card,
.file-log-search-help-popover p,
.file-logs-table-toolbar .fine,
.cache-maintenance-help .subheading,
.path-permissions p {
@@ -622,21 +621,6 @@ p,
gap: 8px;
}
.vh-header-rule-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 8px;
}
.vh-header-rule-title {
font: 600 10px var(--mono);
color: var(--muted);
text-transform: uppercase;
letter-spacing: .45px;
}
.vh-header-rule-fields {
display: grid;
align-items: end;
@@ -1468,11 +1452,6 @@ html[data-dashboard-density=ultra] #panel-overview .dashboard-overview-grid>.car
color: var(--muted);
}
.location-header-editor .vh-header-rule-head>button {
margin-left: auto;
flex: 0 0 auto;
}
.listener-protocol-settings-actions {
display: flex;
gap: 14px;
+101 -36
View File
@@ -775,23 +775,9 @@ button.config-history-day.is-selected,
min-height: 32px;
}
.file-log-search-help-popover {
position: absolute;
z-index: 90;
top: calc(100% + 6px);
inset-inline-end: 0;
display: grid;
gap: 7px;
width: calc(min(420px, calc(100 * var(--rp-vw)) - 36px));
padding: 12px;
border: 1px solid var(--line);
background: var(--panel2);
box-shadow: 0 12px 28px var(--shadow-strong);
}
.file-logs-filter {
display: grid;
grid-template-columns: minmax(180px, 260px) minmax(260px, 1fr) minmax(110px, 150px);
grid-template-columns: minmax(200px, 1.4fr) minmax(200px, 1.4fr) minmax(150px, 1fr) minmax(100px, 130px);
gap: 10px;
align-items: end;
--toolbar-control-height: min(var(--button-min-height), var(--ui-field-min-height));
@@ -799,6 +785,106 @@ button.config-history-day.is-selected,
.file-logs-filter .file-log-search {
grid-column: auto;
min-width: 0;
}
.file-logs-filter .is-disabled {
opacity: .55;
}
.file-log-search-row {
display: grid;
grid-column: 1/-1;
grid-template-columns: minmax(0, 1fr) auto;
align-items: end;
gap: 8px;
}
.file-log-syntax-toggle.active {
border-color: var(--accent);
color: var(--accent);
}
/* Search syntax help: an inline panel inside the workspace (never off-screen). */
.file-log-syntax {
display: grid;
grid-column: 1/-1;
gap: 6px;
padding: 10px 12px;
border: 1px solid var(--line);
border-left: 2px solid var(--accent);
background: var(--panel2);
}
.file-log-syntax[hidden] {
display: none;
}
.file-log-syntax p {
margin: 0;
}
.file-log-syntax-examples {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.file-log-syntax-examples button {
font: 11px var(--mono);
border-radius: 999px;
padding: 3px 10px;
}
.file-log-chips {
display: flex;
flex-wrap: wrap;
grid-column: 1/-1;
gap: 6px;
}
.file-log-chip {
border: 1px solid var(--line);
border-radius: 999px;
background: transparent;
color: var(--muted);
padding: 3px 12px;
font: 600 11px var(--mono);
cursor: pointer;
}
.file-log-chip.active {
border-color: var(--accent);
color: var(--text);
background: var(--panel2);
}
.file-log-chip.is-2xx.active { border-color: var(--green); }
.file-log-chip.is-4xx.active,
.file-log-chip.is-protocol.active { border-color: var(--notice-line); }
.file-log-chip.is-5xx.active { border-color: var(--red); }
#file-log-summary strong {
color: var(--text);
}
.file-log-summary-hint {
color: var(--notice-text);
}
.file-log-summary-hint.is-info {
color: var(--muted);
}
.file-logs-table tr[data-status-class="5xx"] td[data-mobile-column=status],
.file-logs-table tr[data-event] td[data-mobile-column=event] {
color: var(--red);
font-weight: 600;
}
.file-logs-table tr[data-status-class="4xx"] td[data-mobile-column=status] {
color: var(--notice-text);
font-weight: 600;
}
.file-log-column-picker {
@@ -937,29 +1023,8 @@ html[data-table-density=ultra] .file-log-inline-detail pre {
line-height: 1.55;
}
.file-logs-heading-actions .file-log-consolidate {
display: inline-flex;
align-items: center;
gap: .45rem;
padding: .35rem .55rem;
min-height: 0;
color: var(--muted);
font-size: .8rem;
font-weight: 400;
white-space: nowrap;
cursor: pointer;
}
.file-log-consolidate input {
width: 14px;
height: 14px;
margin: 0;
accent-color: var(--accent);
}
.page-footer .footer-update:hover,
.certificate-details summary:hover,
.file-log-consolidate:hover,
.file-log-tab:hover,
.config-history-change-values .diff-after {
color: var(--text);
+52 -19
View File
@@ -440,11 +440,19 @@
#panel-tls .certificate-tabs,
#panel-tls .renewal-meta,
.file-log-column-picker .log-column-options,
.file-log-field,
.file-logs-filter {
.file-log-field {
grid-template-columns: 1fr;
}
.file-logs-filter {
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
}
.file-logs-filter .file-log-source,
.file-logs-filter .file-log-file {
grid-column: 1/-1;
}
#panel-tls .renewal-actions {
justify-content: stretch;
}
@@ -467,10 +475,6 @@
gap: 8px;
}
.file-logs-heading-actions .file-log-consolidate {
margin-inline-end: auto;
}
.file-log-tab {
padding: .6rem .7rem;
}
@@ -524,15 +528,6 @@
gap: 4px;
}
#panel-filelogs .file-logs-heading-actions .file-log-consolidate {
margin-inline-end: auto;
white-space: normal;
}
#panel-filelogs .file-log-search-help-popover {
width: calc(min(320px, calc(100 * var(--rp-vw)) - 54px));
}
#panel-filelogs .file-log-aggregate-form,
#panel-filelogs .file-logs-filter,
#panel-filelogs .file-log-field {
@@ -627,11 +622,43 @@
font-size: 11px;
}
#panel-filelogs .file-logs-table td[data-mobile-column=time],
#panel-filelogs .file-logs-table td[data-mobile-column=vhost] {
#panel-filelogs .file-logs-table td[data-mobile-column=time] {
color: var(--muted);
font-size: 11px;
grid-column: 1/-1;
order: -2;
}
#panel-filelogs .file-logs-table td[data-mobile-column=status] {
order: -1;
text-align: end;
}
#panel-filelogs .file-logs-table td[data-mobile-column=time]:before,
#panel-filelogs .file-logs-table td[data-mobile-column=status]:before {
content: "" !important;
}
#panel-filelogs .file-logs-table td[data-mobile-column=record] {
order: -1;
}
#panel-filelogs .file-logs-table td[data-mobile-column=vhost],
#panel-filelogs .file-logs-table td[data-mobile-column=source] {
color: var(--muted);
font-size: 11px;
}
#panel-filelogs .file-logs-table tbody tr[data-status-class="5xx"],
#panel-filelogs .file-logs-table tbody tr[data-event] {
border-left: 3px solid var(--red);
}
#panel-filelogs .file-logs-table tbody tr[data-status-class="4xx"] {
border-left: 3px solid var(--notice-line);
}
#panel-filelogs .file-logs-table tbody tr[data-status-class="2xx"] {
border-left: 3px solid var(--pill-live-line);
}
#panel-filelogs .file-logs-table tbody tr:not(.file-log-detail-row)>td:before {
@@ -2073,4 +2100,10 @@
.docker-passive-health-editor>summary>span {
flex: 0 0 190px;
}
}
}
@media (max-width: 760px) {
/* Plain request records do not need an "Event: request" line on phones. */
#panel-filelogs .file-logs-table tbody tr:not([data-event]) td[data-mobile-column=event] {
display: none;
}
}
+124 -50
View File
@@ -13,14 +13,12 @@
let visibleColumns = new Set(defaultColumnIds);
let sortBy = "time", sortDescending = true, pendingRefresh = false;
const CONSOLIDATION_STORAGE_KEY = "rp-file-logs-consolidate-vhosts";
const consolidationToggle = $("file-log-consolidate-vhosts");
try {
const saved = localStorage.getItem(CONSOLIDATION_STORAGE_KEY);
if (consolidationToggle && (saved === "1" || saved === "0")) consolidationToggle.checked = saved === "1";
} catch { }
// Sources are shown per log (a site with all its rotations); the File picker
// narrows to one rotation. Rotation 0 is the file being written.
let groups = new Map(), statusFilter = "", eventFilter = "";
const SCOPE_ORDER = ["vhost", "redirect", "host404", "unmatched", "access", "error"];
const sourceSelect = () => $("file-log-source");
const fileSelect = () => $("file-log-file");
function setView(view) {
activeView = view === "counts" ? "counts" : "entries";
for (const name of ["entries", "counts"]) {
@@ -32,41 +30,70 @@
}
if (activeView === "counts" && aggregateField) void refresh(true);
}
function sourceOption(source) {
const grouped = Number(source.member_count) > 1 ? ` · ${fmt(source.member_count)} ${t("fileLogsFiles")}` : "";
const label = `${source.label}${grouped} · ${source.format} · ${bytes(Number(source.size) || 0)}`;
const option = el("option", label); option.value = source.id; return option;
function scopeOf(source) {
if (source.scope) return source.scope;
return String(source.group_id || "").startsWith("vhost:") ? "vhost" : source.kind || "access";
}
function displaySources(sources) {
if (!$("file-log-consolidate-vhosts")?.checked) return sources;
const output = [], groups = new Map();
function groupLabel(group) {
if (group.scope === "access") return t("fileLogsAccessLog");
if (group.scope === "error") return t("fileLogsErrorLog");
if (group.scope === "unmatched") return t("fileLogsUnmatched");
return group.site || group.id.replace(/^vhost:/, "");
}
function fileLabel(source) {
const rotation = Number(source.rotation) || 0;
const name = rotation === 0 ? t("fileLogsCurrentFile") : rotation >= 4294967295 ? source.label : `.${rotation}${source.compressed ? ".gz" : ""}`;
const when = Number(source.modified_ms) ? ` · ${formatDateTime(Number(source.modified_ms))}` : "";
return `${name} · ${bytes(Number(source.size) || 0)}${when}`;
}
function buildGroups(sources) {
const result = new Map();
for (const source of sources) {
if (!String(source.group_id || "").startsWith("vhost:")) { output.push(source); continue; }
const id = source.group_id;
let group = groups.get(id);
if (!group) {
group = { ...source, id, label: id.slice("vhost:".length), size: 0, member_count: 0, compressed: false };
groups.set(id, group); output.push(group);
}
group.size += Number(source.size) || 0; group.member_count += 1;
group.modified_ms = Math.max(Number(group.modified_ms) || 0, Number(source.modified_ms) || 0);
const id = source.group_id || source.id;
let group = result.get(id);
if (!group) { group = { id, scope: scopeOf(source), site: source.site || "", format: source.format, files: [], size: 0, modified_ms: 0 }; result.set(id, group); }
group.files.push(source); group.size += Number(source.size) || 0;
group.modified_ms = Math.max(group.modified_ms, Number(source.modified_ms) || 0);
}
return output;
for (const group of result.values()) group.files.sort((a, b) => (Number(a.rotation) || 0) - (Number(b.rotation) || 0) || (Number(b.modified_ms) || 0) - (Number(a.modified_ms) || 0));
return result;
}
function renderInventory(value) {
inventory = value;
const select = sourceSelect();
let selected = select.value || "all";
const rawSources = Array.isArray(value?.sources) ? value.sources : [];
if ($("file-log-consolidate-vhosts")?.checked && selected !== "all") {
const member = rawSources.find(source => source.id === selected);
if (member?.group_id?.startsWith("vhost:")) selected = member.group_id;
const select = sourceSelect(), previous = select.value || "all", previousFile = fileSelect().value || "all";
groups = buildGroups(Array.isArray(value?.sources) ? value.sources : []);
const options = [Object.assign(el("option", t("fileLogsAllSources")), { value: "all" })];
for (const scope of SCOPE_ORDER) {
const items = [...groups.values()].filter(group => group.scope === scope).sort((a, b) => compareText(groupLabel(a), groupLabel(b), false));
if (!items.length) continue;
const optgroup = document.createElement("optgroup"); optgroup.label = t(`fileLogsScope_${scope}`);
for (const group of items) {
const count = group.files.length > 1 ? ` · ${fmt(group.files.length)} ${t("fileLogsFiles")}` : "";
const option = el("option", `${groupLabel(group)}${count} · ${bytes(group.size)}`); option.value = group.id; optgroup.append(option);
}
options.push(optgroup);
}
const sources = displaySources(rawSources);
const options = [Object.assign(el("option", t("fileLogsAllSources")), { value: "all" }), ...sources.map(sourceOption)];
select.replaceChildren(...options);
select.value = sources.some(source => source.id === selected) ? selected : "all";
// A file id (older bookmark) selects its group.
const owner = [...groups.values()].find(group => group.id === previous || group.files.some(file => file.id === previous));
select.value = owner ? owner.id : "all";
renderFiles(owner && owner.files.some(file => file.id === previousFile) ? previousFile : owner?.files.some(file => file.id === previous) ? previous : "all");
}
function renderFiles(selected = "all") {
const group = groups.get(sourceSelect().value), files = fileSelect();
const options = [Object.assign(el("option", t("fileLogsAllFiles")), { value: "all" })];
if (group) for (const source of group.files) options.push(Object.assign(el("option", fileLabel(source)), { value: source.id }));
files.replaceChildren(...options);
files.value = group?.files.some(file => file.id === selected) ? selected : "all";
files.disabled = !group || group.files.length < 2;
files.closest("label").classList.toggle("is-disabled", files.disabled);
}
function sourceName(id) {
for (const group of groups.values()) {
const file = group.files.find(item => item.id === id);
if (file) return (Number(file.rotation) || 0) === 0 ? groupLabel(group) : `${groupLabel(group)} · .${file.rotation}`;
}
return id || "—";
}
async function loadInventory() {
const value = await api("/api/file-logs");
@@ -112,7 +139,8 @@
function columnValue(entry, id) {
if (id === "time") return entryTime(entry);
if (id === "record") return entrySummary(entry);
if (id === "source") return entry._source || "—";
if (id === "source") return sourceName(entry._source);
if (id === "vhost" && !entry.vhost && (entry.redirect_host || entry.local_host)) return entry.redirect_host ? `↪ ${entry.redirect_host}` : `404 · ${entry.local_host}`;
return displayValue(nestedValue(entry, id));
}
function columnLabel(id) {
@@ -253,6 +281,8 @@
const nodes = [];
entries.forEach((entry, index) => {
const row = el("tr"); row.tabIndex = 0; row.classList.toggle("selected", selectedIndex === index);
const status = Number(entry.status) || 0; if (status >= 100) row.dataset.statusClass = `${Math.floor(status / 100)}xx`;
if (entry.event && entry.event !== "request") row.dataset.event = entry.event;
row.setAttribute("aria-expanded", selectedIndex === index ? "true" : "false");
row.setAttribute("aria-label", entrySummary(entry));
for (const id of ids) {
@@ -272,10 +302,16 @@
}
function queryString() {
const params = new URLSearchParams();
const source = sourceSelect().value || "all";
if (source !== "all") params.set("source", source);
const source = sourceSelect().value || "all", file = fileSelect().value || "all";
if (source !== "all") {
if (file !== "all") params.set("source", file);
else { params.set("source", source); params.set("consolidate_vhosts", "true"); }
}
const q = $("file-log-q").value.trim(); if (q) params.set("q", q);
if ($("file-log-consolidate-vhosts")?.checked) params.set("consolidate_vhosts", "true");
const period = Number($("file-log-period").value) || 0;
if (period > 0) params.set("since_ms", String(Date.now() - period * 1000));
if (statusFilter) params.set("status_class", statusFilter);
if (eventFilter) params.set("event", eventFilter);
if (activeView === "counts" && aggregateField) {
params.set("aggregate_field", aggregateField);
params.set("aggregate_min_count", String(Math.max(2, Number($("file-log-aggregate-min")?.value) || 2)));
@@ -297,22 +333,48 @@
applyFields(Array.isArray(value.fields) ? value.fields : []);
renderRows(Array.isArray(value.entries) ? value.entries : []);
renderAggregation(value.aggregation || null);
const from = lastTotal ? offset + 1 : 0, to = Math.min(offset + currentLimit(), lastTotal);
$("file-log-summary").textContent = t("fileLogsSummary")
.replace("{from}", fmt(from)).replace("{to}", fmt(to)).replace("{total}", fmt(lastTotal))
.replace("{bytes}", bytes(Number(value.scanned_bytes) || 0)).replace("{lines}", fmt(Number(value.scanned_lines) || 0))
+ (value.truncated ? ` · ${t("fileLogsTruncated")}` : "");
renderSummary(value);
const byTime = sortBy === "time" && sortDescending;
$("file-logs-prev").textContent = t(byTime ? "fileLogsNewer" : "previous");
$("file-logs-next").textContent = t(byTime ? "fileLogsOlder" : "next");
$("file-logs-prev").disabled = offset === 0;
$("file-logs-next").disabled = offset + currentLimit() >= lastTotal;
} catch (error) { toast(error.message, true); }
finally { busy = false; $("file-logs-refresh").disabled = false; if (pendingRefresh) { pendingRefresh = false; void refresh(); } }
}
// Status line: what is shown, the time range and which files were read.
function renderSummary(value) {
const summary = $("file-log-summary"); summary.replaceChildren();
const from = lastTotal ? offset + 1 : 0, to = Math.min(offset + currentLimit(), lastTotal);
const main = el("strong", t("fileLogsSummaryShown").replace("{from}", fmt(from)).replace("{to}", fmt(to)).replace("{total}", fmt(lastTotal)));
summary.append(main);
const parts = [];
if (value.newest_ms && value.oldest_ms) parts.push(t("fileLogsSummaryRange").replace("{from}", formatDateTime(Number(value.oldest_ms))).replace("{to}", formatDateTime(Number(value.newest_ms))));
const files = Array.isArray(value.files) ? value.files : [];
const inGroup = groups.has(sourceSelect().value);
const fileName = file => inGroup ? ((Number(file.rotation) || 0) === 0 ? t("fileLogsCurrentFile") : `.${file.rotation}`) : sourceName(file.id);
if (files.length) parts.push(t("fileLogsSummaryFiles").replace("{files}", files.map(fileName).slice(0, 4).join(", ") + (files.length > 4 ? ` +${files.length - 4}` : "")));
parts.push(t("fileLogsSummaryScanned").replace("{lines}", fmt(Number(value.scanned_lines) || 0)).replace("{bytes}", bytes(Number(value.scanned_bytes) || 0)));
summary.append(el("span", ` · ${parts.join(" · ")}`));
const skipped = Number(value.files_skipped) || 0;
if (skipped > 0 || (value.truncated && !value.stopped_at_period)) {
const hint = el("span", "", "file-log-summary-hint");
hint.textContent = value.stopped_at_period
? t("fileLogsSummaryPeriod").replace("{count}", fmt(skipped))
: skipped > 0
? t("fileLogsSummarySkipped").replace("{count}", fmt(skipped))
: t("fileLogsSummaryTruncated");
hint.classList.toggle("is-info", Boolean(value.stopped_at_period));
summary.append(document.createElement("br"), hint);
}
}
function reset() {
inventory = null; offset = 0; lastTotal = 0; currentEntries = []; selectedIndex = null; aggregateField = "";
sortBy = "time"; sortDescending = true; pendingRefresh = false;
preferencesLoaded = false; preferenceSaveRunning = false; preferenceSaveQueued = false;
availableColumns = new Set(defaultColumnIds); visibleColumns = new Set(defaultColumnIds);
sourceSelect().replaceChildren(Object.assign(el("option", t("fileLogsAllSources")), { value: "all" }));
groups = new Map(); statusFilter = ""; eventFilter = ""; syncChips();
sourceSelect().replaceChildren(Object.assign(el("option", t("fileLogsAllSources")), { value: "all" })); renderFiles();
$("file-log-rows").replaceChildren(); $("file-log-aggregate-rows")?.replaceChildren(); renderAggregation(null); syncColumnPicker(); syncHeaders();
}
const fileLogTabs = [$("file-log-tab-entries"), $("file-log-tab-counts")];
@@ -333,12 +395,24 @@
$("file-logs-filter").addEventListener("submit", event => { event.preventDefault(); void refresh(true); });
$("file-log-q").addEventListener("input", () => { clearTimeout(searchTimer); searchTimer = setTimeout(() => void refresh(true), 250); });
$("file-log-limit").addEventListener("change", () => refresh(true));
sourceSelect().addEventListener("change", () => refresh(true));
consolidationToggle?.addEventListener("change", () => {
try { localStorage.setItem(CONSOLIDATION_STORAGE_KEY, consolidationToggle.checked ? "1" : "0"); } catch { }
if (inventory) renderInventory(inventory);
void refresh(true);
});
sourceSelect().addEventListener("change", () => { renderFiles(); void refresh(true); });
fileSelect().addEventListener("change", () => refresh(true));
$("file-log-period").addEventListener("change", () => refresh(true));
function syncChips() {
for (const chip of document.querySelectorAll("#file-log-chips .file-log-chip")) {
const active = (chip.dataset.status || "") === statusFilter && (chip.dataset.event || "") === eventFilter;
chip.setAttribute("aria-pressed", String(active)); chip.classList.toggle("active", active);
}
}
for (const chip of document.querySelectorAll("#file-log-chips .file-log-chip")) {
chip.addEventListener("click", () => { statusFilter = chip.dataset.status || ""; eventFilter = chip.dataset.event || ""; syncChips(); void refresh(true); });
}
// Search syntax help opens inline under the search field (works on phones too).
const syntaxToggle = $("file-log-syntax-toggle"), syntax = $("file-log-syntax");
syntaxToggle.addEventListener("click", () => { syntax.hidden = !syntax.hidden; syntaxToggle.setAttribute("aria-expanded", String(!syntax.hidden)); syntaxToggle.classList.toggle("active", !syntax.hidden); });
for (const example of syntax.querySelectorAll(".file-log-syntax-examples button")) {
example.addEventListener("click", () => { $("file-log-q").value = example.textContent.trim(); syntax.hidden = true; syntaxToggle.setAttribute("aria-expanded", "false"); syntaxToggle.classList.remove("active"); void refresh(true); });
}
$("file-log-aggregate-form")?.addEventListener("submit", event => { event.preventDefault(); aggregateField = $("file-log-aggregate-field").value.trim().toLowerCase(); if (!aggregateField) { renderAggregation(null); return; } void refresh(true); });
$("file-logs-prev").addEventListener("click", () => { offset = Math.max(0, offset - currentLimit()); void refresh(); });
$("file-logs-next").addEventListener("click", () => { if (offset + currentLimit() < lastTotal) { offset += currentLimit(); void refresh(); } });
+53 -21
View File
@@ -1906,21 +1906,6 @@
<h2 data-i18n="fileLogsTitle">Stored log explorer</h2>
</div>
<div class="file-logs-heading-actions">
<details class="file-log-search-help">
<summary class="quiet" data-i18n="fileLogsSearchHelp">Search syntax</summary>
<div class="file-log-search-help-popover">
<strong data-i18n="fileLogsSearchHelpTitle">Kibana-style field search</strong>
<p class="fine" data-i18n="fileLogsSearchHelpText">Use field:value clauses.
Clauses are joined with AND; prefix a clause with ! to exclude it. Quotes
keep spaces together.</p>
<code>req: GET AND !country: PL</code>
<code>status:&gt;=500 AND path:/api/*</code>
<code>error:"connection reset"</code>
</div>
</details>
<label class="file-log-consolidate" title="Consolidate vhost log rotations"><input class="switch"
checked id="file-log-consolidate-vhosts" type="checkbox" /><span
data-i18n="fileLogsConsolidateShort">Merge rotations</span></label>
<button class="outline" data-i18n="refresh" id="file-logs-refresh"
type="button">Refresh</button>
</div>
@@ -1932,9 +1917,18 @@
id="file-log-source">
<option data-i18n="fileLogsAllSources" value="all">All configured files</option>
</select></label>
<label class="file-log-search"><span data-i18n="search">Search</span><input id="file-log-q"
maxlength="512" data-i18n-placeholder="fileLogsSearchPlaceholder"
placeholder="req: GET AND !country: Poland" type="search" /></label>
<label class="file-log-file"><span data-i18n="fileLogsFile">File</span><select
id="file-log-file">
<option data-i18n="fileLogsAllFiles" value="all">All rotations, newest first</option>
</select></label>
<label class="file-log-period"><span data-i18n="fileLogsPeriod">Period</span><select
id="file-log-period">
<option data-i18n="fileLogsPeriodAll" value="0">Everything read</option>
<option data-i18n="fileLogsPeriod15m" value="900">Last 15 minutes</option>
<option data-i18n="fileLogsPeriod1h" value="3600">Last hour</option>
<option data-i18n="fileLogsPeriod24h" value="86400">Last 24 hours</option>
<option data-i18n="fileLogsPeriod7d" value="604800">Last 7 days</option>
</select></label>
<label class="file-log-limit"><span data-i18n="fileLogsPageSize">Page size</span><select
id="file-log-limit">
<option>50</option>
@@ -1942,6 +1936,44 @@
<option>250</option>
<option>500</option>
</select></label>
<div class="file-log-search-row">
<label class="file-log-search"><span data-i18n="search">Search</span><input
id="file-log-q" maxlength="512" data-i18n-placeholder="fileLogsSearchPlaceholder"
placeholder="req: GET AND !country: Poland" type="search" /></label>
<button aria-controls="file-log-syntax" aria-expanded="false"
class="quiet file-log-syntax-toggle" data-i18n="fileLogsSearchHelp"
id="file-log-syntax-toggle" type="button">Search syntax</button>
</div>
<section class="file-log-syntax" hidden id="file-log-syntax">
<strong data-i18n="fileLogsSearchHelpTitle">Kibana-style field search</strong>
<p class="fine" data-i18n="fileLogsSearchHelpText">Use field:value clauses. Clauses are
joined with AND; prefix a clause with ! to exclude it. Quotes keep spaces
together.</p>
<p class="fine" data-i18n="fileLogsSyntaxTryHint">Tap an example to use it:</p>
<div class="file-log-syntax-examples">
<button class="quiet" type="button">status:&gt;=500</button>
<button class="quiet" type="button">req: GET AND !country: PL</button>
<button class="quiet" type="button">status:&gt;=500 AND path:/api/*</button>
<button class="quiet" type="button">client_ip:203.0.113.10</button>
<button class="quiet" type="button">user_agent:*bot*</button>
<button class="quiet" type="button">error:"connection reset"</button>
</div>
</section>
<div aria-label="Status" class="file-log-chips" id="file-log-chips" role="group">
<button aria-pressed="true" class="file-log-chip" data-i18n="fileLogsChipAll"
data-status="" type="button">All</button>
<button aria-pressed="false" class="file-log-chip is-2xx" data-status="2xx"
type="button">2xx</button>
<button aria-pressed="false" class="file-log-chip is-3xx" data-status="3xx"
type="button">3xx</button>
<button aria-pressed="false" class="file-log-chip is-4xx" data-status="4xx"
type="button">4xx</button>
<button aria-pressed="false" class="file-log-chip is-5xx" data-status="5xx"
type="button">5xx</button>
<button aria-pressed="false" class="file-log-chip is-protocol"
data-event="protocol_error" data-i18n="fileLogsChipProtocol"
type="button">Protocol errors</button>
</div>
</form>
<div class="file-log-tabs" role="tablist" aria-label="Stored log views">
<button class="file-log-tab active" id="file-log-tab-entries" type="button" role="tab"
@@ -2008,9 +2040,9 @@
</div>
<p class="empty" data-i18n="fileLogsEmpty" id="file-logs-empty">No records match the current
search.</p>
<div class="file-logs-pager"><button class="quiet" data-i18n="previous" disabled
id="file-logs-prev" type="button">Previous</button><button class="quiet"
data-i18n="next" disabled id="file-logs-next" type="button">Next</button></div>
<div class="file-logs-pager"><button class="quiet" data-i18n="fileLogsNewer" disabled
id="file-logs-prev" type="button">Newer</button><button class="quiet"
data-i18n="fileLogsOlder" disabled id="file-logs-next" type="button">Older</button></div>
</div>
</article>
</section>
-4
View File
@@ -100,10 +100,6 @@ function headerEditors(parent, initial, target = read("headers"), onChange = cha
const holders = {}, adders = {}, emptyStates = {};
const renumber = direction => {
const rows = holders[direction];
[...rows.children].forEach((row, index) => {
const title = row.querySelector(".vh-header-rule-title");
if (title) title.textContent = `${t("headerRule")} ${index + 1}`;
});
if (emptyStates[direction]) emptyStates[direction].hidden = rows.children.length > 0;
};
const sync = () => {
+12 -6
View File
@@ -144,8 +144,8 @@ fn rfc3339_now() -> String {
format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}.{millis:03}Z")
}
async fn open_error_file(path: PathBuf) -> Result<File> {
let file = tokio::task::spawn_blocking(move || -> Result<std::fs::File> {
async fn open_error_file(path: PathBuf) -> Result<(File, RotationCheck)> {
let (file, identity) = tokio::task::spawn_blocking(move || -> Result<(std::fs::File, Option<FileIdentity>)> {
let mut options = std::fs::OpenOptions::new();
options.create(true).append(true).write(true);
#[cfg(unix)]
@@ -161,11 +161,11 @@ async fn open_error_file(path: PathBuf) -> Result<File> {
use std::os::unix::fs::PermissionsExt;
file.set_permissions(std::fs::Permissions::from_mode(0o600))?;
}
Ok(file)
Ok((file, file_identity(&metadata)))
})
.await
.map_err(|_| anyhow::anyhow!("error log open worker failed"))??;
Ok(File::from_std(file))
Ok((File::from_std(file), RotationCheck::new(identity)))
}
fn format_error_event(event: &ErrorEvent, format: ErrorLogFormat) -> Vec<u8> {
@@ -230,7 +230,7 @@ async fn error_log_loop(
errors: Arc<AtomicU64>,
) {
let mut open_path: Option<PathBuf> = None;
let mut file: Option<File> = None;
let mut file: Option<(File, RotationCheck)> = None;
let mut retry_after: Option<Instant> = None;
let mut last_warning: Option<Instant> = None;
loop {
@@ -268,6 +268,12 @@ async fn error_log_loop(
open_path = Some(path.clone());
retry_after = None;
}
// Reopen after external rotation (logrotate `create`, mv, rm).
if let Some((_, rotation)) = file.as_mut() {
if rotation.rotated(&path).await {
file = None;
}
}
if file.is_none() && retry_after.is_none_or(|until| Instant::now() >= until) {
match open_error_file(path.clone()).await {
Ok(opened) => {
@@ -284,7 +290,7 @@ async fn error_log_loop(
}
}
}
let Some(opened) = file.as_mut() else {
let Some((opened, _)) = file.as_mut() else {
write_error_fallback(&event, config.format);
continue;
};
+18
View File
@@ -11,6 +11,12 @@ pub struct LogEntry {
pub authority: Option<String>,
pub matched_by: Option<&'static str>,
pub vhost: Option<String>,
/// Redirect host that answered the request (its own per-site log file).
#[serde(skip_serializing_if = "Option::is_none")]
pub redirect_host: Option<String>,
/// Local 404 host that answered the request (its own per-site log file).
#[serde(skip_serializing_if = "Option::is_none")]
pub local_host: Option<String>,
pub route: Option<String>,
pub cache_effective_enabled: Option<bool>,
pub transform_effective_enabled: Option<bool>,
@@ -263,6 +269,8 @@ impl Logs {
authority,
matched_by: Some(matched_by),
vhost,
redirect_host: None,
local_host: None,
route: None,
cache_effective_enabled: None,
transform_effective_enabled: None,
@@ -368,6 +376,16 @@ fn value_for(entry: &LogEntry, name: &str) -> Value {
.clone()
.map(Value::String)
.unwrap_or(Value::Null),
"redirect_host" => entry
.redirect_host
.clone()
.map(Value::String)
.unwrap_or(Value::Null),
"local_host" => entry
.local_host
.clone()
.map(Value::String)
.unwrap_or(Value::Null),
"route" => entry
.route
.clone()
+2
View File
@@ -261,6 +261,8 @@ fn source_value_name(name: &str) -> bool {
| "outcome"
| "cache"
| "cache_reason"
| "redirect_host"
| "local_host"
)
}
+91 -10
View File
@@ -141,9 +141,74 @@ fn loki_client() -> Result<LokiClient> {
struct FileState {
path: PathBuf,
file: File,
rotation: RotationCheck,
}
/// Identity of an open log file, used to notice external rotation (logrotate
/// `create`, mv, rm): the path then names a different file or none at all.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct FileIdentity {
device: u64,
inode: u64,
}
fn file_identity(metadata: &std::fs::Metadata) -> Option<FileIdentity> {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
Some(FileIdentity {
device: metadata.dev(),
inode: metadata.ino(),
})
}
#[cfg(not(unix))]
{
let _ = metadata;
None
}
}
const ROTATION_CHECK_INTERVAL: Duration = Duration::from_secs(1);
#[derive(Debug)]
struct RotationCheck {
identity: Option<FileIdentity>,
checked: Instant,
}
impl RotationCheck {
fn new(identity: Option<FileIdentity>) -> Self {
Self {
identity,
checked: Instant::now(),
}
}
/// True when `path` no longer refers to the open file. Checked at most once per
/// second, so a busy log costs one `stat` per second.
async fn rotated(&mut self, path: &std::path::Path) -> bool {
let Some(identity) = self.identity else {
return false;
};
if self.checked.elapsed() < ROTATION_CHECK_INTERVAL {
return false;
}
self.checked = Instant::now();
match tokio::fs::symlink_metadata(path).await {
Ok(metadata) => file_identity(&metadata) != Some(identity),
Err(error) => error.kind() == std::io::ErrorKind::NotFound,
}
}
}
const PER_VHOST_OPEN_FILES: usize = 64;
/// File name (without `.jsonl`) of a per-site access log: the vhost id, or
/// `<id>.redirect` / `<id>.host404` for redirect and local 404 hosts (ids cannot
/// contain dots, so these never collide with a vhost), else `_unmatched`.
fn entry_log_name(entry: &LogEntry) -> String {
if let Some(id) = entry.redirect_host.as_deref().filter(|id| crate::config::valid_id(id)) {
return format!("{id}.redirect");
}
if let Some(id) = entry.local_host.as_deref().filter(|id| crate::config::valid_id(id)) {
return format!("{id}.host404");
}
vhost_log_name(entry.vhost.as_deref())
}
fn vhost_log_name(vhost: Option<&str>) -> String {
vhost
.filter(|value| crate::config::valid_id(value))
@@ -155,8 +220,8 @@ struct LogstashState {
stream: TcpStream,
}
async fn open_access_file(path: PathBuf) -> Result<File> {
let file = tokio::task::spawn_blocking(move || -> Result<std::fs::File> {
async fn open_access_file(path: PathBuf) -> Result<(File, RotationCheck)> {
let (file, identity) = tokio::task::spawn_blocking(move || -> Result<(std::fs::File, Option<FileIdentity>)> {
let mut options = std::fs::OpenOptions::new();
options.create(true).append(true).write(true);
#[cfg(unix)]
@@ -172,11 +237,11 @@ async fn open_access_file(path: PathBuf) -> Result<File> {
use std::os::unix::fs::PermissionsExt;
file.set_permissions(std::fs::Permissions::from_mode(0o600))?;
}
Ok(file)
Ok((file, file_identity(&metadata)))
})
.await
.map_err(|_| anyhow::anyhow!("access log open worker failed"))??;
Ok(File::from_std(file))
Ok((File::from_std(file), RotationCheck::new(identity)))
}
async fn sink_loop(
mut rx: mpsc::Receiver<Arc<LogEntry>>,
@@ -187,7 +252,7 @@ async fn sink_loop(
) {
let client = loki_client().ok();
let mut file: Option<FileState> = None;
let mut vhost_files: BTreeMap<PathBuf, File> = BTreeMap::new();
let mut vhost_files: BTreeMap<PathBuf, (File, RotationCheck)> = BTreeMap::new();
let mut vhost_directory: Option<PathBuf> = None;
let mut logstash: Option<LogstashState> = None;
let mut deferred_entry: Option<Arc<LogEntry>> = None;
@@ -210,11 +275,17 @@ async fn sink_loop(
vhost_files.clear();
vhost_directory = None;
let path = PathBuf::from(&config.file.path);
if let Some(state) = file.as_mut() {
if state.path == path && state.rotation.rotated(&path).await {
file = None;
}
}
if file.as_ref().is_none_or(|state| state.path != path) {
file = match open_access_file(path.clone()).await {
Ok(opened) => Some(FileState {
Ok((opened, rotation)) => Some(FileState {
path: path.clone(),
file: opened,
rotation,
}),
Err(error) => {
tracing::warn!(%error, path=%path.display(), "access log file unavailable");
@@ -272,8 +343,12 @@ async fn sink_loop(
if tokio::fs::create_dir_all(&directory).await.is_err() {
failed = true;
} else {
let path =
directory.join(format!("{}.jsonl", vhost_log_name(entry.vhost.as_deref())));
let path = directory.join(format!("{}.jsonl", entry_log_name(&entry)));
if let Some((_, rotation)) = vhost_files.get_mut(&path) {
if rotation.rotated(&path).await {
vhost_files.remove(&path);
}
}
if !vhost_files.contains_key(&path) {
if vhost_files.len() >= PER_VHOST_OPEN_FILES {
if let Some(path) = vhost_files.keys().next().cloned() {
@@ -291,7 +366,7 @@ async fn sink_loop(
}
}
let write_failed = match vhost_files.get_mut(&path) {
Some(opened) => opened.write_all(&jsonl_line).await.is_err(),
Some((opened, _)) => opened.write_all(&jsonl_line).await.is_err(),
None => true,
};
if write_failed {
@@ -303,11 +378,17 @@ async fn sink_loop(
vhost_files.clear();
vhost_directory = None;
let path = PathBuf::from(&config.file.path);
if let Some(state) = file.as_mut() {
if state.path == path && state.rotation.rotated(&path).await {
file = None;
}
}
if file.as_ref().is_none_or(|state| state.path != path) {
file = match open_access_file(path.clone()).await {
Ok(opened) => Some(FileState {
Ok((opened, rotation)) => Some(FileState {
path: path.clone(),
file: opened,
rotation,
}),
Err(error) => {
tracing::warn!(%error, path=%path.display(), "access log file unavailable");
+37
View File
@@ -15,6 +15,8 @@ mod tests {
authority: None,
matched_by: None,
vhost: Some("app".into()),
redirect_host: None,
local_host: None,
route: Some("root".into()),
cache_effective_enabled: Some(true),
transform_effective_enabled: Some(false),
@@ -654,4 +656,39 @@ mod tests {
let jsonl = tokio::fs::read_to_string(path).await.unwrap();
assert_eq!(jsonl.lines().count(), 1);
}
#[tokio::test]
async fn rotated_log_files_are_detected_for_reopening() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("app.jsonl");
let (_file, mut check) = open_access_file(path.clone()).await.unwrap();
check.checked -= ROTATION_CHECK_INTERVAL * 2;
assert!(!check.rotated(&path).await, "same file is not a rotation");
// logrotate `create`: the old file is renamed and a new one created.
std::fs::rename(&path, dir.path().join("app.jsonl.1")).unwrap();
check.checked -= ROTATION_CHECK_INTERVAL * 2;
assert!(check.rotated(&path).await, "missing path means rotated");
std::fs::write(&path, b"").unwrap();
check.checked -= ROTATION_CHECK_INTERVAL * 2;
assert!(check.rotated(&path).await, "new file means rotated");
// Checks are rate-limited.
let (_file, mut fresh) = open_access_file(path.clone()).await.unwrap();
std::fs::remove_file(&path).unwrap();
assert!(!fresh.rotated(&path).await);
}
#[test]
fn redirect_and_local_hosts_get_their_own_log_files() {
let mut item = entry();
assert_eq!(entry_log_name(&item), "app");
item.vhost = None;
item.redirect_host = Some("old-site".into());
assert_eq!(entry_log_name(&item), "old-site.redirect");
item.redirect_host = None;
item.local_host = Some("parking".into());
assert_eq!(entry_log_name(&item), "parking.host404");
item.local_host = Some("../bad".into());
assert_eq!(entry_log_name(&item), "_unmatched");
let json = serde_json::to_value(entry()).unwrap();
assert!(json.get("redirect_host").is_none() && json.get("local_host").is_none());
}
}
+27 -2
View File
@@ -49,6 +49,13 @@ fn read_effective(value: u8) -> Option<bool> {
}
}
/// Redirect or local 404 host that answered instead of a vhost; it gets its own
/// per-site access log file.
#[derive(Debug, Clone)]
pub enum LogSite {
Redirect(String),
LocalHost(String),
}
pub struct Exchange {
pub vhost_metrics: Option<Arc<crate::metrics::VhostMetrics>>,
pub vhost: Option<String>,
@@ -58,6 +65,7 @@ pub struct Exchange {
pub routed: Mutex<Option<Arc<crate::config::CompiledRoute>>>,
/// Request values for response header rules with `%[variables]`.
pub header_vars: Mutex<Option<Arc<crate::headers::RequestVars>>>,
pub log_site: Mutex<Option<LogSite>>,
pub source: AtomicU8,
pub cache_effective_enabled: AtomicU8,
pub transform_effective_enabled: AtomicU8,
@@ -232,7 +240,12 @@ impl Drop for Exchange {
} else {
"complete"
};
if let Some(vhost) = self.vhost.as_ref() {
let log_site = self
.log_site
.get_mut()
.unwrap_or_else(|e| e.into_inner())
.take();
if let Some(vhost) = self.vhost.as_ref().filter(|_| log_site.is_none()) {
self.traffic.push_lazy(|| crate::traffic::Sample {
vhost: vhost.clone(),
route: route.clone(),
@@ -261,7 +274,19 @@ impl Drop for Exchange {
authority: None,
matched_by: None,
cache_reason,
vhost: self.vhost.take(),
vhost: if log_site.is_some() {
None
} else {
self.vhost.take()
},
redirect_host: match &log_site {
Some(LogSite::Redirect(id)) => Some(id.clone()),
_ => None,
},
local_host: match &log_site {
Some(LogSite::LocalHost(id)) => Some(id.clone()),
_ => None,
},
route,
cache_effective_enabled,
transform_effective_enabled,
+1
View File
@@ -13,6 +13,7 @@ mod tests {
route: Mutex::new(None),
routed: Mutex::new(None),
header_vars: Mutex::new(None),
log_site: Mutex::new(None),
source: AtomicU8::new(ExchangeSource::Unresolved as u8),
cache_effective_enabled: AtomicU8::new(0),
transform_effective_enabled: AtomicU8::new(0),
+11
View File
@@ -155,6 +155,17 @@ async fn forward_request(
(Some(vhost), Some(local_host)) => local_host >= vhost,
_ => true,
});
// Requests answered by a redirect or local 404 host are logged under that host.
if let Some(exchange) = request.extensions().get::<Arc<Exchange>>() {
let site = redirect
.map(|(redirect, _)| crate::proxy::body::LogSite::Redirect(redirect.id.clone()))
.or_else(|| {
local_host.map(|item| crate::proxy::body::LogSite::LocalHost(item.id.clone()))
});
if site.is_some() {
*exchange.log_site.lock().unwrap_or_else(|e| e.into_inner()) = site;
}
}
if request.version() == Version::HTTP_2
&& (frontend.is_some_and(|frontend| !frontend.http2_enabled)
|| redirect.is_some_and(|(redirect, _)| !redirect.http2_enabled)
+1
View File
@@ -217,6 +217,7 @@ async fn observe(state: Arc<App>, mut request: Request) -> Response {
route: Mutex::new(None),
routed: Mutex::new(None),
header_vars: Mutex::new(None),
log_site: Mutex::new(None),
source: AtomicU8::new(ExchangeSource::Unresolved as u8),
cache_effective_enabled: AtomicU8::new(0),
transform_effective_enabled: AtomicU8::new(0),