Course › Week 2 · Errors, collections, traits › Day 6 · lesson 13 of 42 · 45 min reading + 2–3 h practice
Build logstat v2
Real flags with clap, a custom error type with thiserror, and tests for the parser.
On this page
Today logstat grows up. Same job, new shape: a library split into modules, flags parsed by clap, one error type written with thiserror, and tests for every part that can be wrong. Everything this week taught, in one project.
It is longer than Day 6, so take it file by file. Each file is shown complete; together they are the whole tool.
#opsMonday 11:05
Omar · backendlogstat is great. Two things would make it the morning check: only errors since yesterday, and which errors, the most frequent messages, so I know if it is one deadlock 400 times or 400 different problems.
Lina · backendAnd if it runs from cron, a wrong flag must fail loudly. I will add features to it later, so tests, please. I do not want to break the parser without knowing.
The layout
The library does the work, main.rs only reads the flags and prints (Day 1’s lib.rs + main.rs shape). Each module has one job:
logstat/
├── Cargo.toml
└── src/
├── main.rs (flags with clap, printing, exit codes)
├── lib.rs (declares the modules)
├── error.rs (LogError: everything that can go wrong)
├── level.rs (Level: the eight Laravel levels)
├── entry.rs (parse one line into an Entry)
├── filter.rs (--level and --since)
└── report.rs (read the log, count, rank messages)
Step 1: two crates
Start from your split logstat, or cargo new logstat. Then add the two dependencies. --features derive turns on clap’s ability to read your flags from a struct.
cargo add clap --features derive
cargo add thiserror
They land in Cargo.toml, at the versions current when this page was written:
[package]
name = "logstat"
version = "0.2.0"
edition = "2024"
[dependencies]
clap = { version = "4.6.10", features = ["derive"] }
thiserror = "2.0.21"
version = "4.6.10" means “4.6.10 or any later 4.x”, like Composer’s ^4.6.10. The exact versions used are recorded in Cargo.lock; commit it for a tool, so every build uses the same ones.
Step 2: one error type, with thiserror
Day 4 implemented Display for the error enum by hand. thiserror writes it for you: #[derive(Error)], and an #[error("…")] line per variant with the message, which can use the variant’s fields by name.
A field named source is understood as the cause: the io::Error underneath. Logging libraries and Week 4’s tools can walk from your error to its cause through it.
use std::io;
use thiserror::Error;
/// Everything that can stop logstat. Each variant prints one sentence.
#[derive(Debug, Error)]
pub enum LogError {
#[error("cannot open {path}: {source}")]
Open { path: String, source: io::Error },
#[error("{path}: line {line}: {source}")]
Read {
path: String,
line: u64,
source: io::Error,
},
#[error("--since must be a date like 2026-11-30, got '{0}'")]
BadDate(String),
}
{0} in the last message is the first unnamed field: BadDate holds the text the user typed.
Step 3: the levels
ValueEnum comes from clap: deriving it lets clap turn --level error into Level::Error, list the accepted values in --help, and reject anything else. It is the same derive idea as Debug, from another crate.
const ALL is a value fixed at compile time, attached to the type: Level::ALL lists every level in report order, so the report loops over it instead of naming each level.
use clap::ValueEnum;
/// The eight levels Laravel writes (they come from Monolog), in order of severity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, ValueEnum)]
pub enum Level {
Debug,
Info,
Notice,
Warning,
Error,
Critical,
Alert,
Emergency,
}
impl Level {
/// Every level, in report order.
pub const ALL: [Level; 8] = [
Level::Debug,
Level::Info,
Level::Notice,
Level::Warning,
Level::Error,
Level::Critical,
Level::Alert,
Level::Emergency,
];
/// The level from its name in a log line: "ERROR" becomes Level::Error.
pub fn from_log(name: &str) -> Option<Level> {
match name {
"DEBUG" => Some(Level::Debug),
"INFO" => Some(Level::Info),
"NOTICE" => Some(Level::Notice),
"WARNING" => Some(Level::Warning),
"ERROR" => Some(Level::Error),
"CRITICAL" => Some(Level::Critical),
"ALERT" => Some(Level::Alert),
"EMERGENCY" => Some(Level::Emergency),
_ => None,
}
}
/// The name as Laravel writes it.
pub fn log_name(self) -> &'static str {
match self {
Level::Debug => "DEBUG",
Level::Info => "INFO",
Level::Notice => "NOTICE",
Level::Warning => "WARNING",
Level::Error => "ERROR",
Level::Critical => "CRITICAL",
Level::Alert => "ALERT",
Level::Emergency => "EMERGENCY",
}
}
}
log_name takes self, not &self: Level is Copy (Day 4), so passing it by value costs nothing.
Step 4: parsing a line
Entry<'a> holds three slices of the line, so it copies no text: reading a 1.4 GB log allocates nothing per line until a message is counted. A struct that holds references needs a lifetime name, the 'a from yesterday: read it as “an Entry borrows from a line”.
Option<Entry<'_>> in the return type says “borrowing from the input, whatever its lifetime is”, the same thing elision does for a plain &str, made visible because it is hidden inside a struct.
strip_prefix('[') returns the rest of the line if it starts with [, or None: the starts_with check and the slice in one step.
use crate::level::Level;
/// The first line of a log entry. Its text is borrowed from the line it was read from.
pub struct Entry<'a> {
pub timestamp: &'a str,
pub level: Level,
pub message: &'a str,
}
/// Parses "[2026-11-30 09:41:03] production.ERROR: message {context}".
/// Returns None for every other line: stack traces, "[stacktrace]", blank lines.
pub fn parse_entry(line: &str) -> Option<Entry<'_>> {
let rest = line.strip_prefix('[')?;
let (timestamp, rest) = rest.split_once("] ")?;
let (head, message) = rest.split_once(": ")?;
let (_environment, level) = head.rsplit_once('.')?;
let level = Level::from_log(level)?;
Some(Entry {
timestamp,
level,
message: without_context(message),
})
}
/// "Booking confirmed {"booking":5521}" becomes "Booking confirmed".
/// The JSON context holds ids, which would make every message unique.
fn without_context(message: &str) -> &str {
match message.split_once(" {") {
Some((text, _context)) => text,
None => message,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_an_entry() {
let entry = parse_entry(
"[2026-11-30 09:41:04] production.INFO: Booking confirmed {\"booking\":5521}",
)
.unwrap();
assert_eq!(entry.timestamp, "2026-11-30 09:41:04");
assert_eq!(entry.level, Level::Info);
assert_eq!(entry.message, "Booking confirmed");
}
#[test]
fn keeps_colons_inside_the_message() {
let entry = parse_entry(
"[2026-11-30 09:41:03] production.ERROR: SQLSTATE[40001]: Serialization failure",
)
.unwrap();
assert_eq!(entry.message, "SQLSTATE[40001]: Serialization failure");
}
#[test]
fn handles_a_dotted_environment_name() {
let entry = parse_entry("[2026-11-30 09:41:03] staging.eu.ERROR: Deadlock").unwrap();
assert_eq!(entry.level, Level::Error);
}
#[test]
fn rejects_everything_else() {
for line in [
"#0 /var/www/app/Actions/ConfirmBooking.php(41): transaction()",
"[stacktrace]",
"\"}",
"",
"[2026-11-30 09:41:03] production.SHOUTING: unknown level",
] {
assert!(parse_entry(line).is_none(), "accepted: {line}");
}
}
}
Its tests sit at the bottom, as on Day 5. The last one checks five kinds of non-entry line in a loop; the second argument of assert! is the message printed if it fails, so you see which line was wrongly accepted.
Step 5: the filters
--since compares timestamps as text: "2026-11-30 09:41:03" >= "2026-11-30" is true, because dates written year-month-day sort like text. That only holds if the date really has that shape, so parse_date checks it before anything uses it.
Slicing by byte position is safe only on ASCII (the panic from Week 1, Day 4), so is_date checks is_ascii() first. The test list includes 2026-11-3ü for that reason.
use crate::entry::Entry;
use crate::error::LogError;
use crate::level::Level;
/// Which entries to count.
pub struct Filter {
pub level: Option<Level>,
/// A date like "2026-11-30": entries on or after it.
pub since: Option<String>,
}
impl Filter {
pub fn accepts(&self, entry: &Entry<'_>) -> bool {
if self.level.is_some() && self.level != Some(entry.level) {
return false;
}
match &self.since {
// "2026-11-30 09:41:03" >= "2026-11-30": dates in this format sort like text.
Some(since) => entry.timestamp >= since.as_str(),
None => true,
}
}
}
/// Checks a --since value: YYYY-MM-DD, month 1 to 12, day 1 to 31.
pub fn parse_date(input: &str) -> Result<String, LogError> {
if is_date(input) {
Ok(input.to_string())
} else {
Err(LogError::BadDate(input.to_string()))
}
}
fn is_date(input: &str) -> bool {
// ASCII only, so the byte positions below can never cut a character in half.
if input.len() != 10 || !input.is_ascii() {
return false;
}
if &input[4..5] != "-" || &input[7..8] != "-" {
return false;
}
let (year, month, day) = (&input[0..4], &input[5..7], &input[8..10]);
if !all_digits(year) || !all_digits(month) || !all_digits(day) {
return false;
}
let month: u32 = month.parse().unwrap_or(0);
let day: u32 = day.parse().unwrap_or(0);
(1..=12).contains(&month) && (1..=31).contains(&day)
}
fn all_digits(text: &str) -> bool {
for c in text.chars() {
if !c.is_ascii_digit() {
return false;
}
}
true
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn accepts_a_date() {
assert_eq!(parse_date("2026-11-30").unwrap(), "2026-11-30");
}
#[test]
fn rejects_what_is_not_a_date() {
for input in [
"30-11-2026",
"2026-13-01",
"2026-11-00",
"2026-1-30",
"2026-+1-05",
"yesterday",
"2026-11-3ü",
] {
assert!(parse_date(input).is_err(), "accepted: {input}");
}
}
}
It checks the shape and the ranges, not the calendar: 2026-02-31 passes. For a log filter that is an honest trade, because no entry has that date and nothing breaks. A tool that does date arithmetic would use the chrono or jiff crate.
Step 6: reading and counting
scan takes reader: impl BufRead (Day 4’s impl Trait): anything that can be read line by line. main passes a file; the tests pass a piece of text with .as_bytes(). One function, tested without touching the disk.
enumerate() gives each line with its position, counted from 0. It replaces last week’s hand-kept counter, which clippy flags here; Week 3 covers it properly.
The message counts are keyed by (Level, String): a pair works as a HashMap key because both parts are Hash + Eq. .copied().unwrap_or(0) turns the Option<&u64> that get returns into a plain number, 0 for a level that never appeared.
use std::collections::HashMap;
use std::io::BufRead;
use crate::entry::parse_entry;
use crate::error::LogError;
use crate::filter::Filter;
use crate::level::Level;
/// The result of reading one log.
#[derive(Default)]
pub struct Report {
/// Entries that passed the filter.
pub entries: u64,
/// Entries the filter left out.
pub filtered_out: u64,
/// Lines that are not an entry's first line: stack traces and the like.
pub other_lines: u64,
by_level: HashMap<Level, u64>,
messages: HashMap<(Level, String), u64>,
}
impl Report {
pub fn count(&self, level: Level) -> u64 {
self.by_level.get(&level).copied().unwrap_or(0)
}
/// The n most frequent messages, most frequent first; ties in alphabetical order.
pub fn top(&self, n: usize) -> Vec<(Level, &str, u64)> {
let mut ranked: Vec<(Level, &str, u64)> = Vec::new();
for ((level, message), count) in &self.messages {
ranked.push((*level, message.as_str(), *count));
}
ranked.sort_by(|a, b| b.2.cmp(&a.2).then(a.1.cmp(b.1)));
ranked.truncate(n);
ranked
}
}
/// Reads a log line by line and counts it. The path is only used in error messages.
pub fn scan(reader: impl BufRead, path: &str, filter: &Filter) -> Result<Report, LogError> {
let mut report = Report::default();
for (index, line) in reader.lines().enumerate() {
let line = line.map_err(|source| LogError::Read {
path: path.to_string(),
line: index as u64 + 1, // enumerate counts from 0; editors count lines from 1
source,
})?;
let Some(entry) = parse_entry(&line) else {
report.other_lines += 1;
continue;
};
if !filter.accepts(&entry) {
report.filtered_out += 1;
continue;
}
report.entries += 1;
*report.by_level.entry(entry.level).or_insert(0) += 1;
*report
.messages
.entry((entry.level, entry.message.to_string()))
.or_insert(0) += 1;
}
Ok(report)
}
#[cfg(test)]
mod tests {
use super::*;
const LOG: &str =
"[2026-11-30 09:41:03] production.ERROR: Deadlock found {\"exception\":\"...\"}
[stacktrace]
#0 /var/www/app/Actions/ConfirmBooking.php(41): transaction()
\"}
[2026-11-30 09:41:04] production.INFO: Booking confirmed {\"booking\":5521}
[2026-12-01 10:15:00] production.ERROR: Deadlock found {\"exception\":\"...\"}
";
fn no_filter() -> Filter {
Filter {
level: None,
since: None,
}
}
#[test]
fn counts_entries_and_other_lines() {
let report = scan(LOG.as_bytes(), "test.log", &no_filter()).unwrap();
assert_eq!(report.entries, 3);
assert_eq!(report.other_lines, 3);
assert_eq!(report.count(Level::Error), 2);
assert_eq!(report.count(Level::Warning), 0);
}
#[test]
fn ranks_messages() {
let report = scan(LOG.as_bytes(), "test.log", &no_filter()).unwrap();
assert_eq!(report.top(1), vec![(Level::Error, "Deadlock found", 2)]);
}
#[test]
fn filters_by_level_and_date() {
let filter = Filter {
level: Some(Level::Error),
since: Some(String::from("2026-12-01")),
};
let report = scan(LOG.as_bytes(), "test.log", &filter).unwrap();
assert_eq!(report.entries, 1);
assert_eq!(report.filtered_out, 2);
}
}
Notice what is not here: no process::exit, no printing. scan returns a Report or a LogError; deciding what to show is main’s job.
Step 7: lib.rs
Five lines of pub mod. //! is a comment that documents the file itself, the way /// documents the item below it.
//! logstat: count a Laravel log by level.
//! The library does the work; src/main.rs only reads the flags and prints.
pub mod entry;
pub mod error;
pub mod filter;
pub mod level;
pub mod report;
Step 8: main.rs with clap
The flags are a struct. #[derive(Parser)] makes clap read them from the command line into it: a field without #[arg] is a positional argument, #[arg(long)] makes --since, an Option makes it optional, and default_value_t gives a default. The /// comments become the --help text.
main returns ExitCode instead of calling process::exit. It ends the program the same way, but only after main has finished, so nothing is cut off halfway. run holds everything that can fail, so ? works in it, and main turns its result into output and an exit code.
use std::fs::File;
use std::io::BufReader;
use std::process::ExitCode;
use clap::Parser;
use logstat::error::LogError;
use logstat::filter::{Filter, parse_date};
use logstat::level::Level;
use logstat::report::{Report, scan};
/// Count a Laravel log by level.
#[derive(Parser)]
#[command(version)]
struct Args {
/// Path to the log, e.g. storage/logs/laravel.log
path: String,
/// Count only entries of this level
#[arg(long, value_enum)]
level: Option<Level>,
/// Count only entries on or after this date (YYYY-MM-DD)
#[arg(long)]
since: Option<String>,
/// Also list the N most frequent messages
#[arg(long, default_value_t = 0)]
top: usize,
}
fn main() -> ExitCode {
let args = Args::parse();
match run(&args) {
Ok(report) => {
print_report(&args, &report);
ExitCode::SUCCESS
}
Err(error) => {
eprintln!("logstat: {error}");
ExitCode::FAILURE
}
}
}
fn run(args: &Args) -> Result<Report, LogError> {
let since = match &args.since {
Some(date) => Some(parse_date(date)?),
None => None,
};
let filter = Filter {
level: args.level,
since,
};
let file = File::open(&args.path).map_err(|source| LogError::Open {
path: args.path.clone(), // the error owns its copy of the path
source,
})?;
scan(BufReader::new(file), &args.path, &filter)
}
fn print_report(args: &Args, report: &Report) {
println!(
"{}: {} entries, {} other lines",
args.path, report.entries, report.other_lines
);
if report.filtered_out > 0 {
println!("({} entries left out by the filters)", report.filtered_out);
}
println!();
for level in Level::ALL {
if args.level.is_some() && args.level != Some(level) {
continue;
}
println!("{:<10} {:>8}", level.log_name(), report.count(level));
}
if args.top > 0 {
println!();
println!("Most frequent messages:");
for (level, message, count) in report.top(args.top) {
println!("{count:>8} {:<9} {message}", level.log_name());
}
}
}
args.path.clone(): the error is returned out of run and must own its copy of the path, while args keeps the original. A reason you can say out loud, so the clone stays.
Run the tests
running 9 tests
test entry::tests::handles_a_dotted_environment_name ... ok
test entry::tests::keeps_colons_inside_the_message ... ok
test entry::tests::parses_an_entry ... ok
test entry::tests::rejects_everything_else ... ok
test filter::tests::accepts_a_date ... ok
test filter::tests::rejects_what_is_not_a_date ... ok
test report::tests::counts_entries_and_other_lines ... ok
test report::tests::filters_by_level_and_date ... ok
test report::tests::ranks_messages ... ok
test result: ok. 9 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00sNine tests across three modules, each next to the code it checks. This is what Lina asked for: change the parser, run cargo test, and know.
Run it
The sample is last week’s log plus four entries from the next morning. Same binary, different flags:
Count a Laravel log by level
Usage: logstat [OPTIONS] <PATH>
Arguments:
<PATH> Path to the log, e.g. storage/logs/laravel.log
Options:
--level <LEVEL> Count only entries of this level [possible values: debug, info, notice, warning, error, critical, alert, emergency]
--since <SINCE> Count only entries on or after this date (YYYY-MM-DD)
--top <TOP> Also list the N most frequent messages [default: 0]
-h, --help Print help
-V, --version Print versionEvery line of this came from the struct and its comments. -h and -V are added by clap.
laravel.log: 13 entries, 13 other lines
DEBUG 0
INFO 5
NOTICE 1
WARNING 3
ERROR 3
CRITICAL 1
ALERT 0
EMERGENCY 0laravel.log: 3 entries, 13 other lines
(10 entries left out by the filters)
ERROR 3
Most frequent messages:
2 ERROR SQLSTATE[40001]: Serialization failure: 1213 Deadlock found when trying to get lock
1 ERROR cURL error 28: Operation timed out after 10001 millisecondsThree errors, two distinct problems: the deadlock twice. The JSON context with ids was stripped, which is what lets two occurrences count as one message.
laravel.log: 4 entries, 13 other lines
(9 entries left out by the filters)
DEBUG 0
INFO 1
NOTICE 0
WARNING 2
ERROR 1
CRITICAL 0
ALERT 0
EMERGENCY 0
Most frequent messages:
2 WARNING Stripe webhook retried
1 INFO Booking confirmedEvery failure, loudly
What Lina’s cron job will see when something is wrong. Exit code 2 is clap’s, for a command typed wrong; 1 is logstat’s, for a run that could not finish.
error: invalid value 'fatal' for '--level <LEVEL>'
[possible values: debug, info, notice, warning, error, critical, alert, emergency]
For more information, try '--help'.
exit code 2logstat: --since must be a date like 2026-11-30, got '01-12-2026'
exit code 1logstat: cannot open storage/logs/laravel.log: No such file or directory (os error 2)
exit code 1error: the following required arguments were not provided:
<PATH>
Usage: logstat <PATH>
For more information, try '--help'.
exit code 2The same flags as an artisan command
Laravel describes a command’s arguments in its signature string:
<?php
protected $signature = 'log:stat {path} {--level=} {--since=} {--top=0}';
public function handle(): int
{
$level = $this->option('level'); // string|null: "fatal" is accepted as it is
$top = (int) $this->option('top'); // "ten" becomes 0, silently
// ...
return self::SUCCESS;
}
clap’s struct is the same idea with types: --level fatal and --top ten are rejected before your code runs, with the list of what is allowed. And thiserror is the Rust counterpart of a small exception hierarchy, except that every caller can see, in the return type, that it may come back.
PracticeTwo extensions, each with a test first
For each: write the failing test, make it pass, run cargo clippy and cargo fmt.
Extension 1: --until
Add --until 2026-11-30: entries on or before that date. Careful: "2026-11-30 09:41:03" <= "2026-11-30" is false as text. Compare only the first 10 characters of the timestamp.
Show a solution for extension 1
pub struct Filter {
pub level: Option<Level>,
pub since: Option<String>,
pub until: Option<String>,
}
// in accepts(), before the match on since:
if let Some(until) = &self.until {
// "2026-11-30 09:41:03" → "2026-11-30". get() returns None instead of panicking
// when the timestamp is shorter than 10 bytes or byte 10 falls inside a character.
match entry.timestamp.get(..10) {
Some(day) if day <= until.as_str() => {}
_ => return false,
}
}
get(..10) is the panic-free slice: Some(&str) or None. Some(day) if … is a match guard: the arm only matches when the condition is also true. In main.rs, add until: Option<String> to Args and pass it through parse_date like since.
Extension 2: exit code 3 on criticals
Bring back last week’s monitoring signal: exit with code 3 when the counted entries include any CRITICAL, ALERT or EMERGENCY. Add Report::has_critical() with a test.
Show a solution for extension 2
// report.rs, in impl Report:
pub fn has_critical(&self) -> bool {
self.count(Level::Critical) + self.count(Level::Alert) + self.count(Level::Emergency) > 0
}
// main.rs, in main:
Ok(report) => {
print_report(&args, &report);
if report.has_critical() {
ExitCode::from(3)
} else {
ExitCode::SUCCESS
}
}
Remember
- A CLI is a struct of flags for clap, a library that returns a
Result, and amainthat maps it to output and an exit code. - Pass
impl BufReadinstead of a file, and the same function is testable with plain text.
Tomorrow is the Week 2 checkpoint: clippy clean, no unwrap outside tests, and every failure ending in a clear message.