Rust Playbook

Course › Week 1 · Basics and ownership › Day 6 · lesson 6 of 42 · 10 min reading + 2 h practice

Build logstat v1

A CLI that reads a laravel.log and counts entries by level, using only what this week taught.

std::env::argsstd::fsBufReadprocess exit codes

On this page
  1. The task
  2. What a Laravel log looks like
  3. Step 1: read the path from the command line
  4. Step 2: stream the file, one line at a time
  5. Step 3: recognise entries and count them
  6. Try it on a real log
  7. The same tool in PHP
  8. Practice
  9. Remember

Today you build a real tool from scratch, using only what this week taught. It is small, it works on a real storage/logs/laravel.log, and it is the first repository of your four.

It is built in three versions of the same file. Each new version is shown whole, with what changed marked.

#opsMonday 10:20

Omar · backendThe production laravel.log is 1.4 GB again. Before I rotate it: how many errors and criticals did we get, compared with warnings? grep -c per level is slow, and it also counts stack-trace lines that happen to contain the word.

Omar · backendSomething we can run on the server: one command, a count per level, and a clear message when the file is missing.

What a Laravel log looks like

Every entry starts with a line like [2026-11-30 09:41:03] production.ERROR: message {context}: a timestamp in brackets, the environment, a dot, the level, a colon. An exception adds more lines after it: [stacktrace], one #0 … line per frame, and a closing "}. Those are part of the entry above them.

So the tool must count only entry lines, which is exactly where grep goes wrong. Here is the sample this page runs on: 9 entries, and 9 other lines that belong to two of them.

laravel.log
[2026-11-30 08:00:01] production.INFO: Scheduled command started {"command":"bookings:expire-holds"}
[2026-11-30 08:00:02] production.INFO: Scheduled command finished {"command":"bookings:expire-holds","expired":3}
[2026-11-30 09:14:27] production.WARNING: Stripe webhook retried {"event":"evt_1QX2","attempt":2}
[2026-11-30 09:41:03] production.ERROR: SQLSTATE[40001]: Serialization failure: 1213 Deadlock found when trying to get lock {"exception":"[object] (Illuminate\\Database\\QueryException(code: 40001): SQLSTATE[40001]: Serialization failure at /var/www/vendor/laravel/framework/src/Illuminate/Database/Connection.php:825)
[stacktrace]
#0 /var/www/vendor/laravel/framework/src/Illuminate/Database/Connection.php(779): Illuminate\\Database\\Connection->runQueryCallback()
#1 /var/www/app/Actions/ConfirmBooking.php(41): Illuminate\\Database\\Connection->transaction()
#2 {main}
"}
[2026-11-30 09:41:04] production.INFO: Booking confirmed {"booking":5521}
[2026-11-30 10:02:59] production.NOTICE: Guest changed dates {"booking":5498}
[2026-11-30 11:30:12] production.ERROR: cURL error 28: Operation timed out after 10001 milliseconds {"exception":"[object] (GuzzleHttp\\Exception\\ConnectException(code: 0): cURL error 28 at /var/www/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php:275)
[stacktrace]
#0 /var/www/app/Channels/AirbnbClient.php(88): GuzzleHttp\\Client->request()
#1 {main}
"}
[2026-11-30 12:00:00] production.CRITICAL: Queue worker stopped {"queue":"channels"}
[2026-11-30 12:00:07] production.INFO: Queue worker started {"queue":"channels"}

Step 1: read the path from the command line

cargo new logstat, then this. env::args() gives the command-line arguments; argument 0 is the program’s own name, so the path is .nth(1), which returns an Option<String>: None when the user typed nothing. You know what to do with an Option: let … else.

eprintln! prints to stderr, where error messages belong, and process::exit(2) ends the program with exit code 2, the usual code for “used the wrong way”. Scripts and Laravel will rely on these codes in Week 4.

logstat/src/main.rsnew file
use std::env;
use std::process;

fn main() {
    let Some(path) = env::args().nth(1) else {
        eprintln!("usage: logstat <path-to-laravel.log>");
        process::exit(2);
    };

    println!("reading {path}");
}
$ cargo run -- laravel.log
reading laravel.log

use std::env; imports a module of the standard library, like PHP’s use for a namespace. Then env::args() is short for std::env::args().

$ cargo run
usage: logstat <path-to-laravel.log>
exit code 2

Without a path: the usage message, and exit code 2.

Step 2: stream the file, one line at a time

Result: Option with a reason

Opening a file can fail: missing, no permission. So File::open returns a Result: an enum like Option, whose two variants are Ok(file) and Err(error). The difference is that the failure carries a reason. You handle it with match, exactly like an Option. Week 2 is all about Result; today, match is enough.

Why line by line

fs::read_to_string(&path) would read the whole file into memory, like PHP’s file_get_contents: 1.4 GB of RAM for a 1.4 GB log. A BufReader reads in small chunks, and .lines() hands you one line at a time, so memory stays flat whatever the file size. Each line is a Result too: reading can fail halfway, for example on bytes that are not valid UTF-8.

logstat/src/main.rschanged since the version above: +24 −1
use std::env;use std::fs::File;use std::io::{BufRead, BufReader};use std::process; fn main() {    let Some(path) = env::args().nth(1) else {        eprintln!("usage: logstat <path-to-laravel.log>");        process::exit(2);    };     println!("reading {path}");    let file = match File::open(&path) {        Ok(file) => file,        Err(error) => {            eprintln!("logstat: cannot open {path}: {error}");            process::exit(1);        }    };     let mut line_number: u64 = 0;     for line in BufReader::new(file).lines() {        line_number += 1;        let line = match line {            Ok(line) => line,            Err(error) => {                eprintln!("logstat: {path}: line {line_number}: {error}");                process::exit(1);            }        };         println!("{line_number}: {} characters", line.len());    }}
$ cargo run -- laravel.log
1: 100 characters
2: 113 characters
3: 97 characters
4: 318 characters
5: 12 characters
6: 134 characters
7: 95 characters
8: 9 characters
9: 2 characters
10: 73 characters
11: 77 characters
12: 257 characters
13: 12 characters
14: 76 characters
15: 9 characters
16: 2 characters
17: 84 characters
18: 80 characters

use std::io::{BufRead, BufReader}; imports two names at once. BufRead is a trait (Week 2): importing it is what makes the .lines() method available.

A line that cannot be read stops the tool with its line number and exit code 1. It never skips it silently: a count that is quietly wrong is worse than no count.

$ cargo run -- storage/logs/laravel.log
logstat: cannot open storage/logs/laravel.log: No such file or directory (os error 2)
exit code 1

A path that does not exist: the operating system’s reason, and exit code 1.

Step 3: recognise entries and count them

The pieces

Level and parse_level are Day 5’s. entry_level is Day 5’s exercise with ?, returning only the level, and one more guard: a colon before the dot means the line is not env.LEVEL:. [stacktrace] starts with [ but has no "] ", so ? returns None for it: correctly not an entry.

Counts holds one number per level plus the other lines. #[derive(Default)] writes a Counts::default() that sets every number to 0. Its add method uses match, so a level added to the enum one day cannot be forgotten here.

print_report puts the rows in an array of pairs, and for (name, count) in rows takes each pair apart. {name:<10} pads to 10 characters on the left, {count:>8} right-aligns in 8.

The whole program

logstat/src/main.rschanged since the version above: +112 −2
use std::env;use std::fs::File;use std::io::{BufRead, BufReader};use std::process; /// The eight levels Laravel writes (they come from Monolog).enum Level {    Debug,    Info,    Notice,    Warning,    Error,    Critical,    Alert,    Emergency,} fn parse_level(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 level of an entry's first line: "[2026-11-30 09:41:03] production.ERROR: …"./// None for everything else: stack traces, "[stacktrace]", blank lines.fn entry_level(line: &str) -> Option<Level> {    if !line.starts_with('[') {        return None;    }    let close = line.find("] ")?;    let rest = &line[close + 2..]; // "production.ERROR: …"    let dot = rest.find('.')?;    let colon = rest.find(": ")?;    if colon < dot {        return None; // a colon before the dot: not "env.LEVEL:"    }    parse_level(&rest[dot + 1..colon])} #[derive(Default)]struct Counts {    debug: u64,    info: u64,    notice: u64,    warning: u64,    error: u64,    critical: u64,    alert: u64,    emergency: u64,    other_lines: u64,} impl Counts {    fn add(&mut self, level: Level) {        match level {            Level::Debug => self.debug += 1,            Level::Info => self.info += 1,            Level::Notice => self.notice += 1,            Level::Warning => self.warning += 1,            Level::Error => self.error += 1,            Level::Critical => self.critical += 1,            Level::Alert => self.alert += 1,            Level::Emergency => self.emergency += 1,        }    }     fn entries(&self) -> u64 {        self.debug            + self.info            + self.notice            + self.warning            + self.error            + self.critical            + self.alert            + self.emergency    }} fn print_report(path: &str, counts: &Counts) {    println!(        "{path}: {} entries, {} other lines",        counts.entries(),        counts.other_lines    );    println!();     let rows = [        ("DEBUG", counts.debug),        ("INFO", counts.info),        ("NOTICE", counts.notice),        ("WARNING", counts.warning),        ("ERROR", counts.error),        ("CRITICAL", counts.critical),        ("ALERT", counts.alert),        ("EMERGENCY", counts.emergency),    ];    for (name, count) in rows {        println!("{name:<10} {count:>8}");    }} fn main() {    let Some(path) = env::args().nth(1) else {        eprintln!("usage: logstat <path-to-laravel.log>");
8 unchanged lines process::exit(2); }; let file = match File::open(&path) { Ok(file) => file, Err(error) => { eprintln!("logstat: cannot open {path}: {error}"); process::exit(1);
} }; let mut counts = Counts::default(); let mut line_number: u64 = 0; for line in BufReader::new(file).lines() {
6 unchanged lines line_number += 1; let line = match line { Ok(line) => line, Err(error) => { eprintln!("logstat: {path}: line {line_number}: {error}"); process::exit(1);
} }; println!("{line_number}: {} characters", line.len()); } match entry_level(&line) { Some(level) => counts.add(level), None => counts.other_lines += 1, } } print_report(&path, &counts);}
$ cargo run -- laravel.log
laravel.log: 9 entries, 9 other lines

DEBUG             0
INFO              4
NOTICE            1
WARNING           1
ERROR             2
CRITICAL          1
ALERT             0
EMERGENCY         0

9 entries and 9 other lines, as counted by hand above. The two ERROR entries brought 9 lines of stack trace with them, and none of those were counted, even the [stacktrace] lines that start with a bracket.

Try it on a real log

Build the fast version once, then run it on a Laravel project’s log:

terminal
cargo build --release
time ./target/release/logstat ~/code/my-laravel-app/storage/logs/laravel.log

The executable in target/release/ is the whole tool. Copy it to a Linux server of the same architecture and it runs there without Rust installed.

Commit it: cargo fmt, cargo clippy, a README with one usage line, and push it as your first repository.

The same tool in PHP

For comparison. It is shorter, because it skips what the Rust version is forced to handle.

logstat.php
<?php

$path = $argv[1] ?? exit("usage: logstat.php <path>\n");
$counts = [];

foreach (new SplFileObject($path) as $line) {      // throws if the file is missing: no friendly message, exit code 255
    if (preg_match('/^\[[^\]]+\] \w+\.([A-Z]+): /', $line, $m)) {
        $counts[$m[1]] = ($counts[$m[1]] ?? 0) + 1; // any word in capitals is accepted as a level
    }
}

print_r($counts);

Three quiet gaps, each of which Rust made you close: the usage message exits with code 0, as if it had succeeded; a typo like EROR becomes a new level instead of being rejected; and the levels you never saw are missing from the report instead of showing 0. None of this is PHP being bad. It is PHP allowing you to skip the question, and Rust not allowing it.

PracticeTwo small extensions to logstat

Make each change, run it on the sample, and keep the tool free of warnings.

Extension 1: the first and last timestamp

Print the time span the log covers: from 2026-11-30 08:00:01 to 2026-11-30 12:00:07. Keep two Option<String> variables, set first once, and update last on every entry. Store only entry timestamps, not stack-trace lines.

Show a solution for extension 1

The timestamp is bytes 1 to 20 of an entry line. Only the changed parts of main are shown:

logstat/src/main.rs (part of main)
    let mut first: Option<String> = None;
    let mut last: Option<String> = None;

    // inside the loop, replacing the match on entry_level:
        match entry_level(&line) {
            Some(level) => {
                counts.add(level);
                let timestamp = line[1..20].to_string();
                if first.is_none() {
                    first = Some(timestamp.clone()); // clone: last needs its own copy too
                }
                last = Some(timestamp);
            }
            None => counts.other_lines += 1,
        }

    // after the loop:
    if let (Some(first), Some(last)) = (&first, &last) {
        println!("from {first} to {last}");
    }

Safe to slice by position: entry_level already checked that the line starts with [ and has "] ", and the timestamp is plain ASCII.

Extension 2: exit code 3 when there are criticals

Monitoring scripts want a signal: after the report, exit with code 3 if there was at least one CRITICAL, ALERT or EMERGENCY entry. Add a method Counts::has_critical(&self) -> bool.

Show a solution for extension 2
logstat/src/main.rs (part)
impl Counts {
    // … add() and entries() as before …

    fn has_critical(&self) -> bool {
        self.critical + self.alert + self.emergency > 0
    }
}

// at the end of main:
    print_report(&path, &counts);
    if counts.has_critical() {
        process::exit(3);
    }

Remember

  • Read big files line by line with BufReader, never all at once.
  • A tool reports every failure on stderr with a non-zero exit code; it never skips a problem silently.

Tomorrow is the Week 1 checkpoint: five broken programs to fix, one for each idea that matters this week.