return old hooks from RelplaceHooks

This commit is contained in:
betrok 2018-08-26 14:40:51 +03:00
parent 7a0120e2c6
commit 13d10d8d89
2 changed files with 12 additions and 3 deletions

View File

@ -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
}

View File

@ -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