Tip for per-test verbose logging in Go
programming 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
Written on Dec 3 2014. Topics: programming, go.
Found a mistake, have a comment? Let me know.

Feedback about page:

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