From 7a0120e2c67ac3a748674a84fbb6ca4fe6231897 Mon Sep 17 00:00:00 2001 From: betrok Date: Wed, 22 Aug 2018 12:10:05 +0300 Subject: [PATCH 1/2] logger.ReplaceHooks --- logger.go | 6 ++++++ logrus_test.go | 16 ++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/logger.go b/logger.go index 7fa8d7d..53bbf95 100644 --- a/logger.go +++ b/logger.go @@ -336,3 +336,9 @@ func (logger *Logger) AddHook(hook Hook) { defer logger.mu.Unlock() logger.Hooks.Add(hook) } + +func (logger *Logger) ReplaceHooks(hooks LevelHooks) { + logger.mu.Lock() + logger.Hooks = hooks + logger.mu.Unlock() +} diff --git a/logrus_test.go b/logrus_test.go index 57fb8d1..7a96686 100644 --- a/logrus_test.go +++ b/logrus_test.go @@ -421,6 +421,22 @@ func TestLoggingRaceWithHooksOnEntry(t *testing.T) { wg.Wait() } +func TestHooksReplace(t *testing.T) { + old, cur := &TestHook{}, &TestHook{} + + logger := New() + logger.AddHook(old) + + hooks := make(LevelHooks) + hooks.Add(cur) + logger.ReplaceHooks(hooks) + + logger.Info("test") + + assert.Equal(t, old.Fired, false) + assert.Equal(t, cur.Fired, true) +} + // Compile test func TestLogrusInterface(t *testing.T) { var buffer bytes.Buffer From 13d10d8d89db071ade54fb0b1667817dd48dc53e Mon Sep 17 00:00:00 2001 From: betrok Date: Sun, 26 Aug 2018 14:40:51 +0300 Subject: [PATCH 2/2] return old hooks from RelplaceHooks --- logger.go | 5 ++++- logrus_test.go | 10 ++++++++-- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/logger.go b/logger.go index 53bbf95..885f150 100644 --- a/logger.go +++ b/logger.go @@ -337,8 +337,11 @@ func (logger *Logger) AddHook(hook Hook) { logger.Hooks.Add(hook) } -func (logger *Logger) ReplaceHooks(hooks LevelHooks) { +// ReplaceHooks replaces the logger hooks and returns the old ones +func (logger *Logger) ReplaceHooks(hooks LevelHooks) LevelHooks { logger.mu.Lock() + oldHooks := logger.Hooks logger.Hooks = hooks logger.mu.Unlock() + return oldHooks } diff --git a/logrus_test.go b/logrus_test.go index 7a96686..f6db6e9 100644 --- a/logrus_test.go +++ b/logrus_test.go @@ -3,6 +3,7 @@ package logrus import ( "bytes" "encoding/json" + "io/ioutil" "strconv" "strings" "sync" @@ -421,20 +422,25 @@ func TestLoggingRaceWithHooksOnEntry(t *testing.T) { wg.Wait() } -func TestHooksReplace(t *testing.T) { +func TestReplaceHooks(t *testing.T) { old, cur := &TestHook{}, &TestHook{} logger := New() + logger.SetOutput(ioutil.Discard) logger.AddHook(old) hooks := make(LevelHooks) hooks.Add(cur) - logger.ReplaceHooks(hooks) + replaced := logger.ReplaceHooks(hooks) logger.Info("test") assert.Equal(t, old.Fired, false) assert.Equal(t, cur.Fired, true) + + logger.ReplaceHooks(replaced) + logger.Info("test") + assert.Equal(t, old.Fired, true) } // Compile test