From 94a8a33e408dc052c698daf1601c9dcd68211d03 Mon Sep 17 00:00:00 2001 From: Eugene Sumin <95425330+e-sumin@users.noreply.github.com> Date: Tue, 12 Mar 2024 09:55:20 +0100 Subject: [PATCH] fix(logs): Fix duplication of logs sent to fluentbit (#2722) * 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> --- pkg/log/log.go | 9 ++++++++- pkg/log/log_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/pkg/log/log.go b/pkg/log/log.go index 8addf8f259..a5155afb82 100644 --- a/pkg/log/log.go +++ b/pkg/log/log.go @@ -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 } diff --git a/pkg/log/log_test.go b/pkg/log/log_test.go index dfbff9f6a6..b6ccf5f52f 100644 --- a/pkg/log/log_test.go +++ b/pkg/log/log_test.go @@ -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) @@ -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{}