Home >Backend Development >Golang >How to Capture and Inspect Logs in Go Tests?
To verify the logs generated by a function under test, it's essential to capture and inspect them. This can be achieved by redirecting the output and comparing it with the expected values.
In the provided example, the readByte function prints the log messages to the standard output. To capture these messages in the test, we can utilize a bytes.Buffer as shown below:
package main import ( "bytes" "fmt" "io" "log" "os" "testing" ) func readByte(/*...*/) { // ... if err != nil { fmt.Println("ERROR") log.Print("Couldn't read first byte") return } // ... } func TestReadByte(t *testing.T) { var buf bytes.Buffer log.SetOutput(&buf) defer func() { log.SetOutput(os.Stderr) }() readByte() t.Log(buf.String()) }
Explanation:
By examining the contents of buf, you can verify if the expected logs were generated by the readByte function. This approach allows you to test log output without modifying the code of the function under test.
The above is the detailed content of How to Capture and Inspect Logs in Go Tests?. For more information, please follow other related articles on the PHP Chinese website!