Skip to content

Commit

Permalink
FilteredLevelWriter writes only logs at Level or above (#573)
Browse files Browse the repository at this point in the history
  • Loading branch information
mitar authored Aug 2, 2023
1 parent 9c29f78 commit 70ac648
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
26 changes: 26 additions & 0 deletions writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,3 +154,29 @@ func ConsoleTestWriter(t TestingLog) func(w *ConsoleWriter) {
w.Out = TestWriter{T: t, Frame: 6}
}
}

// FilteredLevelWriter writes only logs at Level or above to Writer.
//
// It should be used only in combination with MultiLevelWriter when you
// want to write to multiple destinations at different levels. Otherwise
// you should just set the level on the logger and filter events early.
// When using MultiLevelWriter then you set the level on the logger to
// the lowest of the levels you use for writers.
type FilteredLevelWriter struct {
Writer LevelWriter
Level Level
}

// Write writes to the underlying Writer.
func (w *FilteredLevelWriter) Write(p []byte) (int, error) {
return w.Writer.Write(p)
}

// WriteLevel calls WriteLevel of the underlying Writer only if the level is equal
// or above the Level.
func (w *FilteredLevelWriter) WriteLevel(level Level, p []byte) (int, error) {
if level >= w.Level {
return w.Writer.WriteLevel(level, p)
}
return len(p), nil
}
20 changes: 20 additions & 0 deletions writer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,3 +175,23 @@ func TestTestWriter(t *testing.T) {
}

}

func TestFilteredLevelWriter(t *testing.T) {
buf := bytes.Buffer{}
writer := FilteredLevelWriter{
Writer: LevelWriterAdapter{&buf},
Level: InfoLevel,
}
_, err := writer.WriteLevel(DebugLevel, []byte("no"))
if err != nil {
t.Error(err)
}
_, err = writer.WriteLevel(InfoLevel, []byte("yes"))
if err != nil {
t.Error(err)
}
p := buf.Bytes()
if want := "yes"; !bytes.Equal([]byte(want), p) {
t.Errorf("Expected %q, got %q.", want, p)
}
}

0 comments on commit 70ac648

Please sign in to comment.