Skip to content

Commit

Permalink
perf(zap): check level first
Browse files Browse the repository at this point in the history
Signed-off-by: rogerogers <[email protected]>
  • Loading branch information
rogerogers committed Jun 22, 2024
1 parent 6b18af4 commit 04e700c
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 15 deletions.
20 changes: 5 additions & 15 deletions zap/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,10 @@ func (l *Logger) Logf(level hlog.Level, format string, kvs ...interface{}) {
}

func (l *Logger) CtxLogf(level hlog.Level, ctx context.Context, format string, kvs ...interface{}) {
zLevel := hLevelToZapLevel(level)
if !l.config.coreConfigs[0].Lvl.Enabled(zLevel) {
return
}
zapLogger := l.l
if len(l.config.extraKeys) > 0 {
for _, k := range l.config.extraKeys {
Expand Down Expand Up @@ -222,21 +226,7 @@ func (l *Logger) CtxFatalf(ctx context.Context, format string, v ...interface{})
}

func (l *Logger) SetLevel(level hlog.Level) {
var lvl zapcore.Level
switch level {
case hlog.LevelTrace, hlog.LevelDebug:
lvl = zap.DebugLevel
case hlog.LevelInfo:
lvl = zap.InfoLevel
case hlog.LevelWarn, hlog.LevelNotice:
lvl = zap.WarnLevel
case hlog.LevelError:
lvl = zap.ErrorLevel
case hlog.LevelFatal:
lvl = zap.FatalLevel
default:
lvl = zap.WarnLevel
}
lvl := hLevelToZapLevel(level)

l.config.coreConfigs[0].Lvl = lvl

Expand Down
24 changes: 24 additions & 0 deletions zap/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@

package zap

import (
"github.com/cloudwego/hertz/pkg/common/hlog"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)

// InArray check if a string in a slice
func InArray(key ExtraKey, arr []ExtraKey) bool {
for _, k := range arr {
Expand All @@ -23,3 +29,21 @@ func InArray(key ExtraKey, arr []ExtraKey) bool {
}
return false
}

var hLevelToZapLevelMap = map[hlog.Level]zapcore.Level{
hlog.LevelTrace: zapcore.DebugLevel,
hlog.LevelDebug: zapcore.DebugLevel,
hlog.LevelInfo: zapcore.InfoLevel,
hlog.LevelNotice: zapcore.WarnLevel,
hlog.LevelWarn: zapcore.WarnLevel,
hlog.LevelError: zapcore.ErrorLevel,
hlog.LevelFatal: zapcore.FatalLevel,
}

func hLevelToZapLevel(level hlog.Level) zapcore.Level {
if zapLevel, ok := hLevelToZapLevelMap[level]; ok {
return zapLevel
}

return zap.WarnLevel
}

0 comments on commit 04e700c

Please sign in to comment.