Skip to content

Commit 04ea0f4

Browse files
authored
Implement Close() for zerolog.FilteredLevelWriter (#715)
1 parent 0398600 commit 04ea0f4

File tree

3 files changed

+87
-7
lines changed

3 files changed

+87
-7
lines changed

Diff for: console_test.go

+26-7
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,11 @@ package zerolog_test
22

33
import (
44
"bytes"
5+
"encoding/json"
56
"fmt"
67
"io"
78
"os"
9+
"path/filepath"
810
"strings"
911
"testing"
1012
"time"
@@ -315,16 +317,33 @@ func TestConsoleWriter(t *testing.T) {
315317

316318
ts := time.Unix(0, 0)
317319
d := ts.UTC().Format(time.RFC3339)
318-
evt := `{"time": "` + d + `", "level": "debug", "message": "Foobar", "foo": "bar", "caller": "` + cwd + `/foo/bar.go"}`
319-
// t.Log(evt)
320320

321-
_, err = w.Write([]byte(evt))
321+
fields := map[string]interface{}{
322+
"time": d,
323+
"level": "debug",
324+
"message": "Foobar",
325+
"foo": "bar",
326+
"caller": filepath.Join(cwd, "foo", "bar.go"),
327+
}
328+
329+
evt, err := json.Marshal(fields)
330+
if err != nil {
331+
t.Fatalf("Cannot marshal fields: %s", err)
332+
}
333+
334+
_, err = w.Write(evt)
322335
if err != nil {
323336
t.Errorf("Unexpected error when writing output: %s", err)
324337
}
325338

339+
// Define the expected output with forward slashes
326340
expectedOutput := ts.Format(time.Kitchen) + " DBG foo/bar.go > Foobar foo=bar\n"
341+
342+
// Get the actual output and normalize path separators to forward slashes
327343
actualOutput := buf.String()
344+
actualOutput = strings.ReplaceAll(actualOutput, string(os.PathSeparator), "/")
345+
346+
// Compare the normalized actual output to the expected output
328347
if actualOutput != expectedOutput {
329348
t.Errorf("Unexpected output %q, want: %q", actualOutput, expectedOutput)
330349
}
@@ -451,14 +470,14 @@ func TestConsoleWriterConfiguration(t *testing.T) {
451470
})
452471

453472
t.Run("Sets TimeFormat and TimeLocation", func(t *testing.T) {
454-
locs := []*time.Location{ time.Local, time.UTC }
473+
locs := []*time.Location{time.Local, time.UTC}
455474

456475
for _, location := range locs {
457476
buf := &bytes.Buffer{}
458477
w := zerolog.ConsoleWriter{
459-
Out: buf,
460-
NoColor: true,
461-
TimeFormat: time.RFC3339,
478+
Out: buf,
479+
NoColor: true,
480+
TimeFormat: time.RFC3339,
462481
TimeLocation: location,
463482
}
464483

Diff for: diode/diode_test.go

+52
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,58 @@ func TestFatal(t *testing.T) {
7676
}
7777
}
7878

79+
type SlowWriter struct{}
80+
81+
func (rw *SlowWriter) Write(p []byte) (n int, err error) {
82+
time.Sleep(200 * time.Millisecond)
83+
fmt.Print(string(p))
84+
return len(p), nil
85+
}
86+
87+
func TestFatalWithFilteredLevelWriter(t *testing.T) {
88+
if os.Getenv("TEST_FATAL_SLOW") == "1" {
89+
slowWriter := SlowWriter{}
90+
diodeWriter := diode.NewWriter(&slowWriter, 500, 0, func(missed int) {
91+
fmt.Printf("Missed %d logs\n", missed)
92+
})
93+
leveledDiodeWriter := zerolog.LevelWriterAdapter{
94+
Writer: &diodeWriter,
95+
}
96+
filteredDiodeWriter := zerolog.FilteredLevelWriter{
97+
Writer: &leveledDiodeWriter,
98+
Level: zerolog.InfoLevel,
99+
}
100+
logger := zerolog.New(&filteredDiodeWriter)
101+
logger.Fatal().Msg("test")
102+
return
103+
}
104+
105+
cmd := exec.Command(os.Args[0], "-test.run=TestFatalWithFilteredLevelWriter")
106+
cmd.Env = append(os.Environ(), "TEST_FATAL_SLOW=1")
107+
stdout, err := cmd.StdoutPipe()
108+
if err != nil {
109+
t.Fatal(err)
110+
}
111+
err = cmd.Start()
112+
if err != nil {
113+
t.Fatal(err)
114+
}
115+
slurp, err := io.ReadAll(stdout)
116+
if err != nil {
117+
t.Fatal(err)
118+
}
119+
err = cmd.Wait()
120+
if err == nil {
121+
t.Error("Expected log.Fatal to exit with non-zero status")
122+
}
123+
124+
got := cbor.DecodeIfBinaryToString(slurp)
125+
want := "{\"level\":\"fatal\",\"message\":\"test\"}\n"
126+
if got != want {
127+
t.Errorf("Expected output %q, got: %q", want, got)
128+
}
129+
}
130+
79131
func Benchmark(b *testing.B) {
80132
log.SetOutput(io.Discard)
81133
defer log.SetOutput(os.Stderr)

Diff for: writer.go

+9
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,15 @@ func (w *FilteredLevelWriter) WriteLevel(level Level, p []byte) (int, error) {
213213
return len(p), nil
214214
}
215215

216+
// Call the underlying writer's Close method if it is an io.Closer. Otherwise
217+
// does nothing.
218+
func (w *FilteredLevelWriter) Close() error {
219+
if closer, ok := w.Writer.(io.Closer); ok {
220+
return closer.Close()
221+
}
222+
return nil
223+
}
224+
216225
var triggerWriterPool = &sync.Pool{
217226
New: func() interface{} {
218227
return bytes.NewBuffer(make([]byte, 0, 1024))

0 commit comments

Comments
 (0)