Home >Backend Development >Golang >How to Capture and Inspect Logs in Go Tests?

How to Capture and Inspect Logs in Go Tests?

Barbara Streisand
Barbara StreisandOriginal
2024-11-21 02:18:11384browse

How to Capture and Inspect Logs in Go Tests?

Capturing and Inspecting 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:

  • The log.SetOutput(&buf) line redirects the log output to the buf variable.
  • The defer log.SetOutput(os.Stderr) ensures that the log output is restored to its original destination after the test runs.
  • The t.Log(buf.String()) line prints the captured logs to the test log.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn