Go Playbook

Course › Week 2 · Methods, interfaces, errors, tests › Day 6 · lesson 13 of 42 · 35 min reading + 2–3 h practice

Build logstat v2

Real flags with the flag package, errors with context, a parser in its own package, and tests for it.

flagpackageserror wrappingtable tests

On this page
  1. The task
  2. The new layout
  3. Step 1: the parser package
  4. Step 2: test the parser
  5. Step 3: counting that reads any io.Reader
  6. Step 4: test the counting
  7. Step 5: flags
  8. Ship it
  9. The same in a Laravel command
  10. Practice
  11. Remember

logstat v1 from the build day works, but it is one file, it has no options, and nothing tests it. Today it becomes a small tool you would publish: the parser in its own package, counting that can be tested without a file, two flags, and tests for all of it.

Nothing here is new except the flag package, explained where it appears. Everything else is this week: methods, io.Writer, wrapped errors, packages and table tests.

#opsThursday 15:05

Omar · backendlogstat saved me twice this week. Two asks: I only care about warnings and up, and I want “since the deploy at noon”, not the whole file.

Lena · team leadIf it is becoming a tool we rely on, it needs tests before anyone adds a third flag. Put it in the team’s GitHub.

The new layout

logstat/
logstat/
├── go.mod                       (module github.com/you/logstat)
├── main.go                      (flags, exit codes)
├── stats.go                     (counting and the report)
├── stats_test.go
└── internal/
    └── logparse/
        ├── logparse.go          (levels and entry lines)
        └── logparse_test.go

Start a new module with its real path: go mod init github.com/you/logstat (the packages lesson), with your GitHub user in place of you. main.go keeps only what a command needs: reading flags and choosing exit codes. The work moves into stats.go, still in package main, and the log format into internal/logparse, where nothing outside logstat can depend on it.

Step 1: the parser package

This is v1’s Level, isEntry and entryLevel, moved and exported, with two changes. Level has a String method (the interfaces lesson), so the report prints names without a separate slice. ParseEntry returns an Entry with the time as well as the level, which the -since flag needs.

Levels is a function, not an exported variable: an exported slice could be changed by any importer, for every other caller.

logstat/internal/logparse/logparse.gonew file
// Package logparse reads the entries of a Laravel log.
package logparse

import (
	"fmt"
	"strings"
)

// Level is the severity of an entry: the eight levels Laravel writes (they come from Monolog),
// in order of severity.
type Level int

// The levels, from the least to the most severe.
const (
	Debug Level = iota
	Info
	Notice
	Warning
	Error
	Critical
	Alert
	Emergency
)

var levelNames = []string{"DEBUG", "INFO", "NOTICE", "WARNING", "ERROR", "CRITICAL", "ALERT", "EMERGENCY"}

func (l Level) String() string {
	if l < 0 || int(l) >= len(levelNames) {
		return fmt.Sprintf("Level(%d)", int(l))
	}
	return levelNames[l]
}

// Levels returns every level, from Debug to Emergency. It returns a new slice each time, so a
// caller cannot change the list for everyone else.
func Levels() []Level {
	return []Level{Debug, Info, Notice, Warning, Error, Critical, Alert, Emergency}
}

// ParseLevel returns the level with the given name, as Laravel writes it: "ERROR".
func ParseLevel(name string) (Level, error) {
	for i, known := range levelNames {
		if name == known {
			return Level(i), nil
		}
	}
	return Debug, fmt.Errorf("unknown level %q", name)
}

// Entry is what logstat reads from the first line of a log entry.
type Entry struct {
	Time  string // "2026-11-30 09:41:03", as written in the log
	Level Level
}

// 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] == ' '
}

// ParseEntry reads the time and the level of an entry line:
// "[2026-11-30 09:41:03] production.ERROR: message".
func ParseEntry(line string) (Entry, error) {
	if !IsEntry(line) {
		return Entry{}, fmt.Errorf("not the start of an entry: %q", line)
	}
	rest := line[22:] // "production.ERROR: message"
	head, _, found := strings.Cut(rest, ": ")
	if !found {
		return Entry{}, fmt.Errorf("no level in %q", rest)
	}
	_, name, found := strings.Cut(head, ".")
	if !found {
		return Entry{}, fmt.Errorf("no environment before the level in %q", head)
	}
	level, err := ParseLevel(name)
	if err != nil {
		return Entry{}, err
	}
	return Entry{Time: line[1:20], Level: level}, nil
}

Step 2: test the parser

Table tests (the tests lesson): lines that must parse, lines that must not, and the String method’s edge. got != tt.want compares two Entry structs field by field; Go can compare structs whose fields can all be compared.

The rejected lines are the ones logstat met in real logs: the cut-off entry, a level Laravel would never write, a missing environment, stack-trace lines and an empty line. Each was a bug in someone’s first version.

logstat/internal/logparse/logparse_test.gonew file
package logparse

import "testing"

func TestParseEntry(t *testing.T) {
	tests := []struct {
		name string
		line string
		want Entry
	}{
		{
			name: "an error",
			line: "[2026-11-30 09:41:03] production.ERROR: Deadlock found",
			want: Entry{Time: "2026-11-30 09:41:03", Level: Error},
		},
		{
			name: "another environment",
			line: "[2026-11-30 12:00:00] local.EMERGENCY: Disk full",
			want: Entry{Time: "2026-11-30 12:00:00", Level: Emergency},
		},
		{
			name: "a colon in the message",
			line: "[2026-11-30 09:41:03] production.ERROR: SQLSTATE[40001]: Serialization failure",
			want: Entry{Time: "2026-11-30 09:41:03", Level: Error},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got, err := ParseEntry(tt.line)
			if err != nil {
				t.Fatalf("ParseEntry(%q) returned an error: %v", tt.line, err)
			}
			if got != tt.want {
				t.Errorf("ParseEntry(%q) = %+v, want %+v", tt.line, got, tt.want)
			}
		})
	}
}

func TestParseEntryRejects(t *testing.T) {
	lines := []string{
		"[2026-11-30 12:00:07] production.INF",
		"[2026-11-30 12:00:07] production.LOUD: a custom level",
		"[2026-11-30 12:00:07] ERROR: no environment",
		"[stacktrace]",
		"#0 /var/www/app/Actions/ConfirmBooking.php(41): transaction()",
		"",
	}
	for _, line := range lines {
		if _, err := ParseEntry(line); err == nil {
			t.Errorf("ParseEntry(%q) returned no error", line)
		}
	}
}

func TestLevelString(t *testing.T) {
	if got := Critical.String(); got != "CRITICAL" {
		t.Errorf("Critical.String() = %q, want %q", got, "CRITICAL")
	}
	if got := Level(42).String(); got != "Level(42)" {
		t.Errorf("Level(42).String() = %q, want %q", got, "Level(42)")
	}
}
$ go test ./internal/logparse -v
=== RUN   TestParseEntry
=== RUN   TestParseEntry/an_error
=== RUN   TestParseEntry/another_environment
=== RUN   TestParseEntry/a_colon_in_the_message
--- PASS: TestParseEntry (0.00s)
    --- PASS: TestParseEntry/an_error (0.00s)
    --- PASS: TestParseEntry/another_environment (0.00s)
    --- PASS: TestParseEntry/a_colon_in_the_message (0.00s)
=== RUN   TestParseEntryRejects
--- PASS: TestParseEntryRejects (0.00s)
=== RUN   TestLevelString
--- PASS: TestLevelString (0.00s)
PASS
ok  	github.com/you/logstat/internal/logparse	0.002s

Step 3: counting that reads any io.Reader

v1 counted inside run, straight from the file. Now count takes an io.Reader, the reading twin of io.Writer: anything with a Read method, which an *os.File has and so does strings.NewReader("…"). Warnings go to an io.Writer. So the counting can be tested with a string and a strings.Builder, no file and no terminal.

The filter is a struct, so a third option later is a new field, not a new parameter on every function. stats and filter are lowercase: they belong to this command and nothing imports package main.

fmt.Fprintf(w, …) is split over two lines inside its parentheses; gofmt keeps the second line indented. Errors coming up from the scanner are wrapped with %w (the error-wrapping lesson), where v1 used %v.

logstat/stats.gonew file
package main

import (
	"bufio"
	"fmt"
	"io"

	"github.com/you/logstat/internal/logparse"
)

// 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

// filter decides which entries are counted.
type filter struct {
	minLevel logparse.Level
	since    string // "" counts every entry; otherwise the start of a time: "2026-11-30 12:00"
}

// stats is what one pass over a log found.
type stats struct {
	counts     map[logparse.Level]int
	entries    int // entries counted
	skipped    int // entries the filter left out
	otherLines int // stack traces and other lines that belong to an entry
	broken     int // lines that start like an entry but cannot be read
}

// count reads a log and counts its entries. A broken entry is reported on warnings, with its line
// number, and counted; it does not stop the count.
func count(log io.Reader, f filter, warnings io.Writer) (stats, error) {
	s := stats{counts: map[logparse.Level]int{}}
	lineNumber := 0

	scanner := bufio.NewScanner(log)
	scanner.Buffer(make([]byte, 0, 64*1024), maxLineBytes)
	for scanner.Scan() {
		lineNumber++
		line := scanner.Text()
		if !logparse.IsEntry(line) {
			s.otherLines++
			continue
		}
		entry, err := logparse.ParseEntry(line)
		if err != nil {
			if _, err := fmt.Fprintf(warnings, "warning: line %d: %v\n", lineNumber, err); err != nil {
				return s, fmt.Errorf("writing a warning: %w", err)
			}
			s.broken++
			continue
		}
		// Times in this format sort as text: "2026-11-30 11:59:59" < "2026-11-30 12:00".
		if entry.Level < f.minLevel || entry.Time < f.since {
			s.skipped++
			continue
		}
		s.counts[entry.Level]++
		s.entries++
	}
	if err := scanner.Err(); err != nil {
		return s, fmt.Errorf("after line %d: %w", lineNumber, err)
	}
	return s, nil
}

// writeReport writes the stats as a table, one row per level from the filter's minimum up.
func writeReport(w io.Writer, path string, f filter, s stats) error {
	_, err := fmt.Fprintf(w, "%s: %d entries counted, %d left out by the filter, %d other lines, %d broken\n\n",
		path, s.entries, s.skipped, s.otherLines, s.broken)
	if err != nil {
		return err
	}
	for _, level := range logparse.Levels() {
		if level < f.minLevel {
			continue
		}
		if _, err := fmt.Fprintf(w, "%-10v %8d\n", level, s.counts[level]); err != nil {
			return err
		}
	}
	return nil
}

Step 4: test the counting

The sample is a string built from lines joined with +, so each line of the log is one line of code. TestCount checks the numbers and the exact warning text; TestCountFilters checks each filter against the same sample.

These tests are in package main, next to stats.go, and use its unexported names. go test ./... runs both packages.

logstat/stats_test.gonew file
package main

import (
	"strings"
	"testing"

	"github.com/you/logstat/internal/logparse"
)

// sample is a small log: three entries, three lines of a stack trace, and one cut-off entry.
const sample = "[2026-11-30 08:00:01] production.INFO: Scheduled command started\n" +
	"[2026-11-30 09:41:03] production.ERROR: Deadlock found {\"exception\":\"[object] ...\n" +
	"[stacktrace]\n" +
	"#0 /var/www/app/Actions/ConfirmBooking.php(41): transaction()\n" +
	"\"}\n" +
	"[2026-11-30 12:00:00] production.CRITICAL: Queue worker stopped\n" +
	"[2026-11-30 12:00:07] production.INF\n"

func TestCount(t *testing.T) {
	var warnings strings.Builder
	got, err := count(strings.NewReader(sample), filter{}, &warnings)
	if err != nil {
		t.Fatalf("count returned an error: %v", err)
	}

	if got.entries != 3 || got.otherLines != 3 || got.broken != 1 {
		t.Errorf("count = %d entries, %d other lines, %d broken; want 3, 3, 1", got.entries, got.otherLines, got.broken)
	}
	if got.counts[logparse.Error] != 1 || got.counts[logparse.Critical] != 1 {
		t.Errorf("counts = %v, want one ERROR and one CRITICAL", got.counts)
	}
	want := "warning: line 7: no level in \"production.INF\"\n"
	if warnings.String() != want {
		t.Errorf("warnings = %q, want %q", warnings.String(), want)
	}
}

func TestCountFilters(t *testing.T) {
	tests := []struct {
		name        string
		f           filter
		wantEntries int
		wantSkipped int
	}{
		{name: "no filter", f: filter{}, wantEntries: 3, wantSkipped: 0},
		{name: "warnings and above", f: filter{minLevel: logparse.Warning}, wantEntries: 2, wantSkipped: 1},
		{name: "since noon", f: filter{since: "2026-11-30 12:00"}, wantEntries: 1, wantSkipped: 2},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			var warnings strings.Builder
			got, err := count(strings.NewReader(sample), tt.f, &warnings)
			if err != nil {
				t.Fatalf("count returned an error: %v", err)
			}
			if got.entries != tt.wantEntries || got.skipped != tt.wantSkipped {
				t.Errorf("count = %d counted, %d skipped; want %d, %d", got.entries, got.skipped, tt.wantEntries, tt.wantSkipped)
			}
		})
	}
}
$ go test ./...
ok  	github.com/you/logstat	0.003s
ok  	github.com/you/logstat/internal/logparse	0.003s

One ok line per package with tests. If a test fails, the line says FAIL and the failures are printed above it, as in the tests lesson.

Step 5: flags

The flag package

flag.String(name, default, help) declares a flag and returns a *string (the pointers lesson). It has to be a pointer: the value is filled in later, by flag.Parse(), which reads os.Args. After it, *minName is the value, and flag.Arg(0) and flag.NArg() are the arguments left after the flags.

flag.Usage is the function the package calls to print help; replacing it adds the usage line above the generated list of flags. flag.CommandLine.Output() is stderr. On an unknown flag, flag.Parse prints the problem and the usage, and exits with code 2 by itself. On -h it prints the usage and exits with 0.

main now only validates and maps to exit codes: 2 for every way of using the tool wrongly, 1 when the work itself failed.

logstat/main.gorewritten
package main

import (
	"flag"
	"fmt"
	"os"

	"github.com/you/logstat/internal/logparse"
)

func main() {
	minName := flag.String("min", "DEBUG", "count only entries at this level or above")
	since := flag.String("since", "", "count only entries at or after this time, like \"2026-11-30 12:00\"")
	flag.Usage = func() {
		fmt.Fprintln(flag.CommandLine.Output(), "usage: logstat [-min LEVEL] [-since TIME] <path to laravel.log>")
		flag.PrintDefaults()
	}
	flag.Parse()

	if flag.NArg() != 1 {
		flag.Usage()
		os.Exit(2)
	}
	minLevel, err := logparse.ParseLevel(*minName)
	if err != nil {
		fmt.Fprintln(os.Stderr, "logstat: -min:", err)
		os.Exit(2)
	}
	if *since != "" && len(*since) < len("2026-11-30") {
		fmt.Fprintln(os.Stderr, "logstat: -since: want a date like 2026-11-30, or a date and time like \"2026-11-30 12:00\"")
		os.Exit(2)
	}

	if err := run(flag.Arg(0), filter{minLevel: minLevel, since: *since}); err != nil {
		fmt.Fprintln(os.Stderr, "logstat:", err)
		os.Exit(1)
	}
}

func run(path string, f filter) error {
	file, err := os.Open(path)
	if err != nil {
		return err
	}
	defer file.Close()

	s, err := count(file, f, os.Stderr)
	if err != nil {
		return fmt.Errorf("reading %s: %w", path, err)
	}
	return writeReport(os.Stdout, path, f, s)
}
$ ./logstat laravel.log
warning: line 18: no level in "production.INF"
laravel.log: 9 entries counted, 0 left out by the filter, 9 other lines, 1 broken

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

The same numbers as v1 on the same sample, and the warning, which now comes from count, on stderr.

Warnings and above, since noon

$ ./logstat -min WARNING -since "2026-11-30 11:00" laravel.log
warning: line 18: no level in "production.INF"
laravel.log: 2 entries counted, 7 left out by the filter, 9 other lines, 1 broken

WARNING           0
ERROR             1
CRITICAL          1
ALERT             0
EMERGENCY         0

Two entries are counted: the ERROR at 11:30 and the CRITICAL at 12:00. The other seven are below WARNING, before 11:00, or both. Flags come before the path: the flag package stops reading flags at the first argument that is not one.

Wrong uses

$ ./logstat -min LOUD laravel.log
logstat: -min: unknown level "LOUD"
exit code 2
$ ./logstat -level ERROR laravel.log
flag provided but not defined: -level
usage: logstat [-min LEVEL] [-since TIME] <path to laravel.log>
  -min string
    	count only entries at this level or above (default "DEBUG")
  -since string
    	count only entries at or after this time, like "2026-11-30 12:00"
exit code 2

An unknown flag: the flag package’s own message, the usage, and exit code 2, without a line of our code.

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

A missing file is still a failure of the work, exit code 1, with the operating system’s reason.

Ship it

terminal
gofmt -l .
go vet ./...
staticcheck ./...
go test ./...
go install

The first three must print nothing, the tests must pass. go install builds logstat and puts it in ~/go/bin, so it runs from any folder. Once the repository is on GitHub, anyone with Go can install it with go install github.com/you/logstat@latest, the same way you installed staticcheck.

The same in a Laravel command

app/Console/Commands/LogStat.php
<?php
final class LogStat extends Command
{
    protected $signature = 'log:stat {path} {--min=DEBUG} {--since=}';

    public function handle(LogParser $parser): int
    {
        $min = Level::tryFrom($this->option('min'));
        if ($min === null) {
            $this->error('unknown level');
            return self::INVALID;                // exit code 2
        }
        // ...
        return self::SUCCESS;
    }
}

An artisan command gives you flags, help and exit codes for free, and it is the right tool inside a Laravel app. The Go version runs where there is no app: on a log server, in a cron job of another team, on a machine with no PHP.

The test story is the same as in Laravel: keep the parsing in a class (a package) that knows nothing about the console, and test it directly. What Go adds is io.Reader and io.Writer everywhere, so even the counting and the report need no fake filesystem.

PracticeLearn Go with Tests: Structs, methods & interfaces; one more flag

Do Structs, methods & interfaces in Learn Go with Tests. It builds table tests around an interface, the same shape as today.

Exercise: -env

Add a -env flag: when it is set, count only entries of that environment (production, staging). It needs Entry to carry the environment, a field on filter, a test case in each test file, and nothing in main.go but the flag. Write the test cases first and watch them fail.

Remember

  • main reads flags and picks exit codes (2 for wrong use, 1 for failed work); everything else lives in functions that take an io.Reader and an io.Writer.
  • Every line a real log broke your parser with becomes a test case.

Tomorrow is the checkpoint: five broken programs from this week, and logstat v2’s exit check.