Go Playbook

Course › Week 1 · Basics and a first CLI › Day 6 · lesson 6 of 42 · 15 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.

os.Argsos.Openbufio.Scannerdeferos.Exit

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. Step 4: the line that is too long
  7. Try it on a real log
  8. The same tool in PHP
  9. Practice
  10. Remember

Today you build a real tool from scratch, using only what this week taught plus a few standard library functions, each explained where it appears. 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 four 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 copy to the server: one binary, 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 complete entries, 9 lines that belong to two of them, and one entry cut off after production.INF, the way a log looks after the disk filled up.

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.INF
[2026-11-30 12:00:09] production.INFO: Queue worker started {"queue":"channels"}

Step 1: read the path from the command line

mkdir logstat, cd logstat, go mod init logstat, then this. os.Args is a []string of the command-line arguments. Element 0 is the program’s own name, so one path means a length of 2.

fmt.Fprintln(os.Stderr, …) prints to stderr, where error messages belong; Println is the same thing for stdout. os.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.

From here on the page builds the program with go build and runs ./logstat, so the real exit code shows. go run would report a failure as exit status 2 and exit with 1 itself.

logstat/main.gonew file
package main

import (
	"fmt"
	"os"
)

func main() {
	if len(os.Args) != 2 {
		fmt.Fprintln(os.Stderr, "usage: logstat <path to laravel.log>")
		os.Exit(2)
	}
	path := os.Args[1]

	fmt.Println("reading", path)
}
$ ./logstat laravel.log
reading laravel.log
$ ./logstat
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

Why line by line

os.ReadFile 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 bufio.Scanner reads the file in small chunks and hands you one line at a time, so memory stays flat whatever the file size. scanner.Scan() moves to the next line and returns false at the end; scanner.Text() is the current line, without its newline.

Scan returns false for two reasons: the end of the file, or a read error. scanner.Err() after the loop tells them apart: nil means the end. Skip that check and a failed read looks like a short file, a silent wrong answer.

defer, and why main calls run

os.Open returns the file and an error, the shape from the errors lesson. An open file must be closed. defer file.Close() schedules the call for the moment run returns, whichever return that is. Writing it on the line right after the successful open is the Go habit, like a finally you cannot forget.

os.Exit ends the program at once and does not run deferred calls. So the work lives in run, which returns an error, and only main decides the message and the exit code. Every tool in this course has that shape. (The error of Close itself is ignored here: the file was only read, so there is nothing to lose. A file you write is different; Week 3 handles it.)

logstat/main.gochanged since the version above: +25 −3
package main import (	"bufio"	"fmt"	"os") func main() {	if len(os.Args) != 2 {		fmt.Fprintln(os.Stderr, "usage: logstat <path to laravel.log>")		os.Exit(2)	}	path := os.Args[1] 	fmt.Println("reading", path)	if err := run(os.Args[1]); err != nil {		fmt.Fprintln(os.Stderr, "logstat:", err)		os.Exit(1)	}} func run(path string) error {	file, err := os.Open(path)	if err != nil {		return err	}	defer file.Close() 	scanner := bufio.NewScanner(file)	lines := 0	for scanner.Scan() {		lines++	}	if err := scanner.Err(); err != nil {		return fmt.Errorf("reading %s after line %d: %v", path, lines, err)	} 	fmt.Println(path, "has", lines, "lines")	return nil}
$ ./logstat laravel.log
laravel.log has 19 lines

19 lines: 10 that start an entry and 9 that belong to two of them.

$ ./logstat storage/logs/laravel.log
logstat: open storage/logs/laravel.log: no such file or directory
exit code 1

A path that does not exist: the operating system’s reason, with the path in it, and exit code 1. os.Open’s error already names the file, so run returns it as it is.

Step 3: recognise entries and count them

The pieces

Level and its constants are the named type from the structs lesson, now with all eight levels. levelNames is a slice, so it cannot be a const: a var at the top of the file is a package-level variable, visible to every function in the file. The comment above a type, a variable or a function starts with its name; that is Go’s documentation style, read by go doc and your editor.

isEntry checks the shape of the start of the line: [, then 19 characters of timestamp, then ] . Reading line[20] gives one byte of the string. The len(line) > 22 check comes first, so a short line can never index past its end and panic. [stacktrace] is too short, and #0 … does not start with [.

entryLevel uses strings.Cut(s, sep), which splits a string at the first sep and returns the part before, the part after, and whether sep was found at all. The found check is what turns the cut-off line into an error instead of a wrong level. The loop compares the name with each known name, and Level(i) converts the position into a Level.

A broken entry is reported on stderr with its line number and counted, never skipped silently: a count that is quietly wrong is worse than no count.

The program

logstat/main.gochanged since the version above: +70 −8
package main import (	"bufio"	"fmt"	"os") 	"strings") // Level is one of the eight levels Laravel writes (they come from Monolog), in order of severity.type Level int const (	Debug Level = iota	Info	Notice	Warning	Error	Critical	Alert	Emergency) // levelNames[level] is the name Laravel writes for that level.var levelNames = []string{"DEBUG", "INFO", "NOTICE", "WARNING", "ERROR", "CRITICAL", "ALERT", "EMERGENCY"} func main() {	if len(os.Args) != 2 {		fmt.Fprintln(os.Stderr, "usage: logstat <path to laravel.log>")
12 unchanged lines os.Exit(2) } if err := run(os.Args[1]); err != nil { fmt.Fprintln(os.Stderr, "logstat:", err) os.Exit(1) }} func run(path string) error { file, err := os.Open(path) if err != nil { return err
} defer file.Close() counts := map[Level]int{} entries, otherLines, broken := 0, 0, 0 lineNumber := 0 scanner := bufio.NewScanner(file) lines := 0 for scanner.Scan() { lines++ lineNumber++ line := scanner.Text() if !isEntry(line) { otherLines++ continue } level, err := entryLevel(line) if err != nil { fmt.Fprintf(os.Stderr, "logstat: line %d: %v\n", lineNumber, err) broken++ continue } counts[level]++ entries++ } if err := scanner.Err(); err != nil { return fmt.Errorf("reading %s after line %d: %v", path, lines, err) } fmt.Println(path, "has", lines, "lines") return fmt.Errorf("reading %s after line %d: %v", path, lineNumber, err) } fmt.Printf("%s: %d entries, %d other lines, %d broken\n\n", path, entries, otherLines, broken) for i, name := range levelNames { fmt.Printf("%-10s %8d\n", name, counts[Level(i)]) } return nil} // isEntry reports whether a line starts a log entry: "[2026-11-30 09:41:03] ...". Lines of a stack// trace, "[stacktrace]" and the closing "}" belong to the entry above them.func isEntry(line string) bool { return len(line) > 22 && line[0] == '[' && line[20] == ']' && line[21] == ' '} // entryLevel reads the level of an entry line: "[2026-11-30 09:41:03] production.ERROR: message".func entryLevel(line string) (Level, error) { rest := line[22:] // "production.ERROR: message" head, _, found := strings.Cut(rest, ": ") if !found { return Debug, fmt.Errorf("no level in %q", rest) } _, name, found := strings.Cut(head, ".") if !found { return Debug, fmt.Errorf("no environment before the level in %q", head) } for i, known := range levelNames { if name == known { return Level(i), nil } } return Debug, fmt.Errorf("unknown level %q", name)}
$ ./logstat laravel.log
logstat: line 18: no level in "production.INF"
laravel.log: 9 entries, 9 other lines, 1 broken

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

9 entries, 9 other lines and 1 broken entry, 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. The warning about line 18 went to stderr while the file was read, the report to stdout at the end; a script can keep them apart with 2> errors.txt.

Step 4: the line that is too long

A real failure

Laravel writes an entry’s whole context on its first line. A job that logs the API response it could not process can make that one line hundreds of kilobytes long. Here is the same program on a log with one 200 KB line:

$ ./logstat laravel.log
logstat: line 18: no level in "production.INF"
logstat: reading laravel.log after line 19: bufio.Scanner: token too long
exit code 1

A bufio.Scanner refuses lines longer than 64 KB by default. Because the program checks scanner.Err(), it stops with a clear message and exit code 1. Without that check, it would print counts for the first 19 lines as if the file ended there.

The fix: a larger limit

scanner.Buffer(buffer, max) sets the scanner’s starting buffer and the longest line it will accept. The buffer grows only when a long line arrives, so memory stays small for normal lines. The limit is a named constant with a comment saying why it exists.

logstat/main.gochanged since the version above: +5
23 unchanged linespackage main import ( "bufio" "fmt" "os" "strings") // Level is one of the eight levels Laravel writes (they come from Monolog), in order of severity.type Level int const ( Debug Level = iota Info Notice Warning Error Critical Alert Emergency)
// levelNames[level] is the name Laravel writes for that level.var levelNames = []string{"DEBUG", "INFO", "NOTICE", "WARNING", "ERROR", "CRITICAL", "ALERT", "EMERGENCY"} // maxLineBytes is the longest line logstat accepts. Laravel writes a whole entry's context on its// first line, and a job that logs an API response can make that line very long.const maxLineBytes = 16 * 1024 * 1024 func main() { if len(os.Args) != 2 { fmt.Fprintln(os.Stderr, "usage: logstat <path to laravel.log>")
17 unchanged lines os.Exit(2) } if err := run(os.Args[1]); err != nil { fmt.Fprintln(os.Stderr, "logstat:", err) os.Exit(1) }} func run(path string) error { file, err := os.Open(path) if err != nil { return err } defer file.Close() counts := map[Level]int{} entries, otherLines, broken := 0, 0, 0
lineNumber := 0 scanner := bufio.NewScanner(file) scanner.Buffer(make([]byte, 0, 64*1024), maxLineBytes) for scanner.Scan() { lineNumber++ line := scanner.Text()
48 unchanged lines if !isEntry(line) { otherLines++ continue } level, err := entryLevel(line) if err != nil { fmt.Fprintf(os.Stderr, "logstat: line %d: %v\n", lineNumber, err) broken++ continue } counts[level]++ entries++ } if err := scanner.Err(); err != nil { return fmt.Errorf("reading %s after line %d: %v", path, lineNumber, err) } fmt.Printf("%s: %d entries, %d other lines, %d broken\n\n", path, entries, otherLines, broken) for i, name := range levelNames { fmt.Printf("%-10s %8d\n", name, counts[Level(i)]) } return nil} // isEntry reports whether a line starts a log entry: "[2026-11-30 09:41:03] ...". Lines of a stack// trace, "[stacktrace]" and the closing "}" belong to the entry above them.func isEntry(line string) bool { return len(line) > 22 && line[0] == '[' && line[20] == ']' && line[21] == ' '} // entryLevel reads the level of an entry line: "[2026-11-30 09:41:03] production.ERROR: message".func entryLevel(line string) (Level, error) { rest := line[22:] // "production.ERROR: message" head, _, found := strings.Cut(rest, ": ") if !found { return Debug, fmt.Errorf("no level in %q", rest) } _, name, found := strings.Cut(head, ".") if !found { return Debug, fmt.Errorf("no environment before the level in %q", head) } for i, known := range levelNames { if name == known { return Level(i), nil } } return Debug, fmt.Errorf("unknown level %q", name)}
$ ./logstat laravel.log
logstat: line 18: no level in "production.INF"
laravel.log: 10 entries, 9 other lines, 1 broken

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

The long line is counted as the 10th complete entry, an ERROR. A line over 16 MB still stops the tool with the same clear error, which is the right answer for a file that is no longer a sane log.

Try it on a real log

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

terminal
go build
time ./logstat ~/code/my-laravel-app/storage/logs/laravel.log

logstat is the whole tool. To run it on the production server, build for the server’s system from your machine with GOOS=linux GOARCH=amd64 go build, copy the file, and run it there with no Go installed.

Commit it: go vet ./..., staticcheck ./..., 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 Go version handles.

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
    }                                               // a cut-off entry is skipped without a word
}

ksort($counts);                                     // alphabetical, not by severity
foreach ($counts as $level => $count) {
    printf("%-10s %8d\n", $level, $count);
}

SplFileObject streams line by line too, and has no 64 KB limit. What it does not give you: a usage message on stderr with exit code 2, a clear message instead of an uncaught exception, broken entries reported instead of skipped, and levels in order of severity.

The real difference shows on the server. The PHP script needs PHP installed there; the Go one is a single file you copy.

PracticeExtend logstat: a --since date, and the busiest hour

Two additions, both using only this week’s Go. Do the first; the second is a stretch.

Exercise 1: only entries since a date

Accept an optional second argument, a date like 2026-11-30 12:00. When it is given, count only entries whose timestamp is at or after it. Timestamps in this format sort as text, so you can compare line[1:20] with the argument directly using >=, no date parsing needed. A second argument shorter than 10 characters is a usage error with exit code 2.

Exercise 2: the busiest hour

Count entries per hour, using line[1:14] (2026-11-30 09) as a map key, and print the hour with the most entries after the report. When two hours tie, print the earlier one, so the output never depends on the map’s order.

Remember

  • Stream big files with bufio.Scanner, set its line limit with Buffer, and always check scanner.Err().
  • Put the work in a run function that returns an error; only main prints it and calls os.Exit, because os.Exit skips deferred calls.
  • defer the close on the line right after the open succeeds.

Tomorrow is the checkpoint: five broken programs that use everything from this week.