Skip to content

Commit

Permalink
Add logg.ErrStopLogEntry
Browse files Browse the repository at this point in the history
As a way to stop a log entry from being passed on in the log handler chain
  • Loading branch information
bep committed Nov 6, 2023
1 parent 7a1b4c9 commit 6a2e1c0
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
23 changes: 23 additions & 0 deletions handlers/multi/multi_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,26 @@ func TestMultiModifyEntry(t *testing.T) {
qt.Assert(t, b.Entries[0].Fields[0].Name, qt.Equals, "initial")
qt.Assert(t, b.Entries[0].Fields[1].Name, qt.Equals, "added")
}

func TestStopEntry(t *testing.T) {
var a logg.HandlerFunc = func(e *logg.Entry) error {
if e.Fields[0].Value == "v2" {
return logg.ErrStopLogEntry
}
return nil
}

b := memory.New()

l := logg.New(
logg.Options{
Level: logg.LevelInfo,
Handler: multi.New(a, b),
})

l.WithLevel(logg.LevelInfo).WithField("v", "v1").Log(logg.String("text"))
l.WithLevel(logg.LevelInfo).WithField("v", "v2").Log(logg.String("text"))
l.WithLevel(logg.LevelInfo).WithField("v", "v3").Log(logg.String("text"))

qt.Assert(t, b.Entries, qt.HasLen, 2)
}
8 changes: 7 additions & 1 deletion logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,10 @@ func (l *logger) WithError(err error) *Entry {
return NewEntry(l).WithError(err)
}

// ErrStopLogEntry is a sentinel error that can be returned from a
// handler to stop the entry from being passed to the next handler.
var ErrStopLogEntry = fmt.Errorf("stop log entry")

// log the message, invoking the handler.
func (l *logger) log(e *Entry, s fmt.Stringer) {
if e.Level < l.Level {
Expand All @@ -148,6 +152,8 @@ func (l *logger) log(e *Entry, s fmt.Stringer) {
e.finalize(finalized, s.String())

if err := l.Handler.HandleLog(finalized); err != nil {
stdlog.Printf("error logging: %s", err)
if err != ErrStopLogEntry {
stdlog.Printf("error logging: %s", err)
}
}
}

0 comments on commit 6a2e1c0

Please sign in to comment.