Skip to content

Commit

Permalink
ref(log): reduce struct props
Browse files Browse the repository at this point in the history
  • Loading branch information
aymanbagabas committed Feb 27, 2023
1 parent 44db2e7 commit c158121
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 9 deletions.
14 changes: 6 additions & 8 deletions log.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,8 @@ type logger struct {
mu *sync.RWMutex

isDiscard uint32
aLevel int32

level Level
level int32
prefix string
timeFunc TimeFunction
timeFormat string
Expand All @@ -53,7 +52,7 @@ func New(opts ...LoggerOption) Logger {
l := &logger{
b: bytes.Buffer{},
mu: &sync.RWMutex{},
level: InfoLevel,
level: int32(InfoLevel),
}

for _, opt := range opts {
Expand All @@ -65,7 +64,7 @@ func New(opts ...LoggerOption) Logger {
}

l.SetOutput(l.w)
l.SetLevel(l.level)
l.SetLevel(Level(l.level))

if l.timeFunc == nil {
l.timeFunc = time.Now
Expand All @@ -84,7 +83,7 @@ func (l *logger) log(level Level, msg interface{}, keyvals ...interface{}) {
}

// check if the level is allowed
if atomic.LoadInt32(&l.aLevel) > int32(level) {
if atomic.LoadInt32(&l.level) > int32(level) {
return
}

Expand Down Expand Up @@ -225,15 +224,14 @@ func (l *logger) SetReportCaller(report bool) {
func (l *logger) GetLevel() Level {
l.mu.RLock()
defer l.mu.RUnlock()
return l.level
return Level(l.level)
}

// SetLevel sets the current level.
func (l *logger) SetLevel(level Level) {
l.mu.Lock()
defer l.mu.Unlock()
l.level = level
atomic.StoreInt32(&l.aLevel, int32(level))
atomic.StoreInt32(&l.level, int32(level))
}

// GetPrefix returns the current prefix.
Expand Down
28 changes: 28 additions & 0 deletions log_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,31 @@ func TestSubLogger(t *testing.T) {
})
}
}

func TestWrongLevel(t *testing.T) {
var buf bytes.Buffer
cases := []struct {
name string
expected string
level Level
}{
{
name: "wrong level",
expected: "",
level: Level(999),
},
{
name: "wrong level negative",
expected: "INFO info\n",
level: Level(-999),
},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
buf.Reset()
l := New(WithOutput(&buf), WithLevel(c.level))
l.Info("info")
assert.Equal(t, c.expected, buf.String())
})
}
}
2 changes: 1 addition & 1 deletion options.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func WithTimeFormat(format string) LoggerOption {
// default is InfoLevel.
func WithLevel(level Level) LoggerOption {
return func(l *logger) {
l.level = level
l.level = int32(level)
}
}

Expand Down

0 comments on commit c158121

Please sign in to comment.