Home
Tip for per-test verbose logging in Go
One way to narrow down a problem when debugging a test is to add logging with e.g. fmt.Printf().
The problem with this approach is lack of selectivity: imagine you have 100 tests and only 1 test fails. For debugging the issue you only need to see logs when executing that 1 test but you’ll drown in log output from all 100 tests.
My solution: control logging state with global variable verboseLog and allow toggling this flag per test.
Something like this:
var (
    verboseLog = false
)

func myCodeWithBugs(s string) {
    if verboseLog {
        fmt.Printf("s: %s\n", s)
    }
    ...
}

func TestMyCode(t *testing.T) {
    var tests = []struct {
        ... test fields
        debug bool
    }{
        { ..., false }, // without verbose logging
        { ..., true },  // with verbose logging
    }
    for _, test := range tests {
        verboseLog = test.debug
        ...
    }
}
programming go
Feb 12 2023

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you: