sirupsen / logrus

Structured, pluggable logging for Go.
MIT License
24.59k stars 2.27k forks source link

Use for range to output two identical logs #1432

Closed iarno closed 5 months ago

iarno commented 5 months ago

TestEntryWriter

# logrus_test.go:687

type channelWriter chan []byte

func (cw channelWriter) Write(p []byte) (int, error) {
    cw <- p
    fmt.Printf("%p \n", p)
    return len(p), nil
}

func TestEntryWriter(t *testing.T) {
    cw := channelWriter(make(chan []byte, 3))
    log := New()
    log.Out = cw
    log.Formatter = new(JSONFormatter)
    _, err := log.WithField("foo", "bar").WriterLevel(WarnLevel).Write([]byte("hello1\n"))
    if err != nil {
        t.Error("unexecpted error", err)
    }

    _, err = log.WithField("foo", "bar").WriterLevel(WarnLevel).Write([]byte("hello2\n"))
    if err != nil {
        t.Error("unexecpted error", err)
    }

    for v := range cw {
        fmt.Println(string(v))
    }
}

output:

$ go test -timeout 30s -run ^TestEntryWriter$ github.com/sirupsen/logrus -v -count=1
=== RUN   TestEntryWriter
0xc0000286c0 
0xc0000286c0 
{"foo":"bar","level":"warning","msg":"hello2","time":"2024-04-26T18:27:26+08:00"}

{"foo":"bar","level":"warning","msg":"hello2","time":"2024-04-26T18:27:26+08:00"}

FAIL    github.com/sirupsen/logrus      3.702s