rust 41 lines · 7 steps

Parsing access logs with a lazy regex in Rust

A compile-once regex extracts named fields from an access log line into a typed struct.

Explained by highlit
1use once_cell::sync::Lazy;
2use regex::Regex;
3 
4static LOG_LINE: Lazy<Regex> = Lazy::new(|| {
5 Regex::new(
6 r#"(?x)
7 ^(?P<ip>\S+)\s+
8 \S+\s+\S+\s+
9 \[(?P<timestamp>[^\]]+)\]\s+
10 "(?P<method>[A-Z]+)\s+(?P<path>\S+)\s+HTTP/(?P<version>[\d.]+)"\s+
11 (?P<status>\d{3})\s+
12 (?P<bytes>\d+|-)
13 "#,
14 )
15 .expect("log line regex is valid")
16});
17 
18#[derive(Debug)]
19pub struct AccessEntry {
20 pub ip: String,
21 pub timestamp: String,
22 pub method: String,
23 pub path: String,
24 pub version: String,
25 pub status: u16,
26 pub bytes: Option<u64>,
27}
28 
29pub fn parse_access_log(line: &str) -> Option<AccessEntry> {
30 let caps = LOG_LINE.captures(line.trim())?;
31 
32 Some(AccessEntry {
33 ip: caps["ip"].to_owned(),
34 timestamp: caps["timestamp"].to_owned(),
35 method: caps["method"].to_owned(),
36 path: caps["path"].to_owned(),
37 version: caps["version"].to_owned(),
38 status: caps["status"].parse().ok()?,
39 bytes: caps["bytes"].parse().ok(),
40 })
41}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Lazy statics compile an expensive resource like a regex exactly once, on first use, then share it everywhere.
  2. 2Named capture groups map directly to struct fields, keeping parsing readable and self-documenting.
  3. 3Returning Option and using the ? operator lets a parser fail gracefully on any malformed line.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Parsing access logs with a lazy regex in Rust — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code