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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Lazy statics compile an expensive resource like a regex exactly once, on first use, then share it everywhere.
- 2Named capture groups map directly to struct fields, keeping parsing readable and self-documenting.
- 3Returning Option and using the ? operator lets a parser fail gracefully on any malformed line.
Related explainers
python
from configparser import ConfigParser, ExtendedInterpolation from pathlib import Path
Layered INI config loading in Python
configuration
parsing
defaults
Intermediate
8 steps
rust
use axum::{ body::Body, extract::State, http::{header, StatusCode},
Streaming NDJSON from Postgres in Axum
streaming
backpressure
async
Advanced
9 steps
python
from urllib.parse import urlparse class RobotsRules:
Parsing and applying a robots.txt file
parsing
longest-prefix-match
state-machine
Intermediate
10 steps
rust
use std::net::{IpAddr, SocketAddr}; use axum::extract::{ConnectInfo, FromRequestParts}; use axum::http::request::Parts;
How a custom ClientIp extractor works in Axum
extractor
http-headers
proxy-forwarding
Intermediate
8 steps
rust
use axum::{ extract::State, response::sse::{Event, KeepAlive, Sse}, Json,
Proxying an SSE chat stream in Axum
server-sent-events
streaming
async-generators
Advanced
10 steps
rust
use std::collections::HashMap; fn decode_component(input: &str) -> String { let bytes = input.as_bytes();
Parsing a URL query string in Rust
url-encoding
byte-parsing
iterators
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/parsing-access-logs-with-a-lazy-regex-in-rust-explained-rust-6430/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.