It is often helpful to output additional information when running tests. Go provides access to the testing logger via a set of methods on *testing.T. While you can use fmt.Println and fmt.Printf, it is better to use the testing logger because its output is only displayed when a test fails (or when you turn on verbose output).
The most commonly-used test logging methods are Log and Logf, which provide unformatted and formatted output. The log message is indented and prefixed with the file name and line number of the log statement.
If your log output is processed by external tools, you can include structured data in your output with the Attr method. It takes two string parameters, a key and a value. The meaning of the key/value pair is up to you; the only limitation that the key cannot contain any whitespace characters. The method writes a line with the following values, separated by whitespace: === ATTR, the name of the test, the key, and the value.
Finally, the Output method provides access to the test logger’s underlying io.Writer. Like Log and Logf, anything written using this io.Writer is indented, but there’s no file name/line number prefix.
func TestLogging(t *testing.T) {
fmt.Println("fmt.Println does work, but it's always there and unindented")
t.Log("This is a simple string message")
t.Logf("This message has %d %s specifiers in it", 2, "formatting")
t.Attr("key_for_processing", "value_for_processing with whitespace")
t.Output().Write([]byte("a final entry"))
}
Here’s the output for this test:
$ go test -v
=== RUN TestLogging
fmt.Println does work, but it's always there and unindented
logging_test.go:10: This is a simple string message
logging_test.go:11: This message has 2 formatting specifiers in it
=== ATTR TestLogging key_for_processing value_for_processing with whitespace
a final entry
--- PASS: TestLogging (0.00s)
PASS
ok example.com/studynotes/logging 0.204s