From 094bf181b1c85c12c2843d7c30099ec652d70df8 Mon Sep 17 00:00:00 2001 From: Qingshan Luo Date: Wed, 3 Aug 2022 17:46:44 +0800 Subject: [PATCH] Allows changing the logger level at runtime. --- log.go | 11 ++++++----- logger.go | 5 +++-- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/log.go b/log.go index 7de94d4..36ac8dc 100644 --- a/log.go +++ b/log.go @@ -21,6 +21,7 @@ import ( "io" "os" "sync" + "sync/atomic" "time" "github.com/edoger/zkits-logger/internal" @@ -184,7 +185,7 @@ type Log interface { // and each independent Logger shares the same core instance. type core struct { name string - level Level + level uint32 formatter Formatter writer io.Writer levelWriter map[Level]io.Writer @@ -203,7 +204,7 @@ type core struct { func newCore(name string) *core { return &core{ name: name, - level: TraceLevel, + level: uint32(TraceLevel), formatter: DefaultJSONFormatter(), writer: os.Stdout, levelWriter: make(map[Level]io.Writer), @@ -430,7 +431,7 @@ func (o *log) Log(level Level, args ...interface{}) { // Uses the given parameters to record a log of the specified level. func (o *log) log(level Level, args ...interface{}) { - if !o.core.level.IsEnabled(level) { + if !Level(atomic.LoadUint32(&o.core.level)).IsEnabled(level) { return } o.record(level, fmt.Sprint(args...)) @@ -448,7 +449,7 @@ func (o *log) Logln(level Level, args ...interface{}) { // Uses the given parameters to record a log of the specified level. func (o *log) logln(level Level, args ...interface{}) { - if !o.core.level.IsEnabled(level) { + if !Level(atomic.LoadUint32(&o.core.level)).IsEnabled(level) { return } s := fmt.Sprintln(args...) @@ -467,7 +468,7 @@ func (o *log) Logf(level Level, format string, args ...interface{}) { // Uses the given parameters to record a log of the specified level. func (o *log) logf(level Level, format string, args ...interface{}) { - if !o.core.level.IsEnabled(level) { + if !Level(atomic.LoadUint32(&o.core.level)).IsEnabled(level) { return } o.record(level, fmt.Sprintf(format, args...)) diff --git a/logger.go b/logger.go index 7d77054..7730a8c 100644 --- a/logger.go +++ b/logger.go @@ -18,6 +18,7 @@ import ( "io" stdlog "log" "os" + "sync/atomic" "time" "github.com/edoger/zkits-logger/internal" @@ -110,12 +111,12 @@ type logger struct { // GetLevel returns the current logger level. func (o *logger) GetLevel() Level { - return o.core.level + return Level(atomic.LoadUint32(&o.core.level)) } // SetLevel sets the current logger level. func (o *logger) SetLevel(level Level) Logger { - o.core.level = level + atomic.StoreUint32(&o.core.level, uint32(level)) return o }