Skip to content

Commit

Permalink
Allows changing the logger level at runtime.
Browse files Browse the repository at this point in the history
  • Loading branch information
edoger committed Aug 3, 2022
1 parent 6bb257e commit 094bf18
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 7 deletions.
11 changes: 6 additions & 5 deletions log.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"io"
"os"
"sync"
"sync/atomic"
"time"

"github.com/edoger/zkits-logger/internal"
Expand Down Expand Up @@ -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
Expand All @@ -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),
Expand Down Expand Up @@ -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...))
Expand All @@ -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...)
Expand All @@ -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...))
Expand Down
5 changes: 3 additions & 2 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"io"
stdlog "log"
"os"
"sync/atomic"
"time"

"github.com/edoger/zkits-logger/internal"
Expand Down Expand Up @@ -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
}

Expand Down

0 comments on commit 094bf18

Please sign in to comment.