Skip to content

Commit

Permalink
fix(logs): Fix duplication of logs sent to fluentbit (#2722)
Browse files Browse the repository at this point in the history
* Prevent adding one hook multiple times

* Add tests checking that hooks are not duplicated

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
  • Loading branch information
e-sumin and mergify[bot] committed Mar 12, 2024
1 parent 13628c0 commit 94a8a33
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
9 changes: 8 additions & 1 deletion pkg/log/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -264,11 +264,18 @@ func cloneGlobalLogger() *logrus.Logger {
cloned.SetLevel(log.Level)
cloned.SetOutput(log.Out)
cloned.ExitFunc = log.ExitFunc

globalHooks := make(map[logrus.Hook]bool)

for _, hooks := range log.Hooks {
for _, hook := range hooks {
cloned.Hooks.Add(hook)
globalHooks[hook] = true
}
}

for hook := range globalHooks {
cloned.Hooks.Add(hook)
}

return cloned
}
27 changes: 27 additions & 0 deletions pkg/log/log_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,29 @@ func (s *LogSuite) TestLogLevel(c *C) {
}

func (s *LogSuite) TestCloneGlobalLogger(c *C) {
done := make(chan struct{})
defer close(done)

capturedMessages := make([]*logrus.Entry, 0)
newTestHook := func(ctx context.Context) *FluentbitHook {
ec := make(chan *logrus.Entry, defaultEntryBufferCount)

go func(in <-chan *logrus.Entry) {
for {
select {
case e := <-in:
capturedMessages = append(capturedMessages, e)
case <-done:
return
}
}
}(ec)

return &FluentbitHook{logs: ec}
}

hook := newTestHook(context.TODO())
log.AddHook(hook)
actual := cloneGlobalLogger()
c.Assert(actual.Formatter, Equals, log.Formatter)
c.Assert(actual.ReportCaller, Equals, log.ReportCaller)
Expand All @@ -216,6 +239,10 @@ func (s *LogSuite) TestCloneGlobalLogger(c *C) {
c.Assert(actual.Level, Not(Equals), log.Level)
c.Assert(actual.Out, Not(Equals), log.Out)
c.Assert(actual.Hooks, Not(DeepEquals), log.Hooks)

log.Println("Test message")
c.Assert(len(capturedMessages), Equals, 1)
c.Assert(capturedMessages[0].Message, Equals, "Test message")
}

type testLogHook struct{}
Expand Down

0 comments on commit 94a8a33

Please sign in to comment.