diff --git a/exported.go b/exported.go index f0b327b..017c30c 100644 --- a/exported.go +++ b/exported.go @@ -268,15 +268,3 @@ func Panicln(args ...interface{}) { func Fatalln(args ...interface{}) { std.Fatalln(args...) } - -func Lock() { - if !std.mu.disabled { - std.mu.Lock() - } -} - -func Unlock() { - if !std.mu.disabled { - std.mu.Unlock() - } -} diff --git a/logger.go b/logger.go index 91b460e..70aff9d 100644 --- a/logger.go +++ b/logger.go @@ -406,6 +406,24 @@ func (logger *Logger) ReplaceHooks(hooks LevelHooks) LevelHooks { return oldHooks } +// ReplaceHook replaces the logger hook and returns hook exists or not +func (logger *Logger) ReplaceHook(hook Hook) bool { + logger.mu.Lock() + oldHooks := logger.Hooks + hasReplaced := false + for _, level := range hook.Levels() { + for index, h := range oldHooks[level] { + if h == hook { + oldHooks[level] = append(oldHooks[level][:index], oldHooks[level][index+1:]...) + hasReplaced = true + break + } + } + } + logger.mu.Unlock() + return hasReplaced +} + // SetBufferPool sets the logger buffer pool. func (logger *Logger) SetBufferPool(pool BufferPool) { logger.mu.Lock() diff --git a/logger_test.go b/logger_test.go index 6765213..bbde0e5 100644 --- a/logger_test.go +++ b/logger_test.go @@ -8,7 +8,6 @@ import ( "path/filepath" "runtime" "strconv" - "sync" "testing" "time" @@ -133,11 +132,7 @@ func TestLogger_concurrentLock(t *testing.T) { time.Sleep(1 * time.Minute) } -var traceLock = &sync.Mutex{} - func AddTraceIdHook(traceId string) Hook { - defer traceLock.Unlock() - traceLock.Lock() traceHook := newTraceIdHook(traceId) if StandardLogger().Hooks == nil { hooks := new(LevelHooks) @@ -148,23 +143,7 @@ func AddTraceIdHook(traceId string) Hook { } func RemoveTraceHook(hook Hook) { - allHooks := StandardLogger().Hooks - func() { - defer Unlock() - Lock() - for key, hooks := range allHooks { - replaceHooks := hooks - for index, h := range hooks { - if h == hook { - replaceHooks = append(hooks[:index], hooks[index:]...) - break - } - } - allHooks[key] = replaceHooks - } - }() - - StandardLogger().ReplaceHooks(allHooks) + StandardLogger().ReplaceHook(hook) } type TraceIdHook struct { @@ -192,7 +171,6 @@ func (t TraceIdHook) Fire(entry *Entry) error { type LogFormatter struct{} - func (s *LogFormatter) Format(entry *Entry) ([]byte, error) { timestamp := time.Now().Format("2006-01-02 15:04:05") var file string