Skip to content

Commit

Permalink
日志报错等级优化
Browse files Browse the repository at this point in the history
  • Loading branch information
feyman committed Jan 26, 2024
1 parent 763740e commit 90767a1
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 49 deletions.
36 changes: 24 additions & 12 deletions gorm.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@ package logit

import (
"context"
"errors"
"time"

"github.com/axiaoxin-com/goutils"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"gorm.io/gorm"
gormlogger "gorm.io/gorm/logger"
)

Expand Down Expand Up @@ -42,6 +44,8 @@ type GormLoggerOptions struct {
// 配置日志字段 key 的名称
// Optional.
EncoderConfig *zapcore.EncoderConfig
// RecordNotFoundErr 错误等级
RecordNotFoundErrLevel string
}

// GormLogger 使用 zap 来打印 gorm 的日志
Expand All @@ -52,8 +56,9 @@ type GormLogger struct {
// 日志级别
logLevel zapcore.Level
// 指定慢查询时间
slowThreshold time.Duration
_logger *zap.Logger
slowThreshold time.Duration
_logger *zap.Logger
recordNotFoundErrLevel string
}

var gormLogLevelMap = map[gormlogger.LogLevel]zapcore.Level{
Expand Down Expand Up @@ -109,27 +114,34 @@ func (g GormLogger) Trace(ctx context.Context, begin time.Time, fc func() (strin
l := g.CtxLogger(ctx).Named("sql")
switch {
case err != nil:
l.Error("sql trace", zap.String("sql", sql), zap.Float64("latency", latency), zap.Int64("rows", rows), zap.String("error", err.Error()))
level := zap.ErrorLevel
if errors.Is(err, gorm.ErrRecordNotFound) {
var err1 error
if level, err1 = zapcore.ParseLevel(g.recordNotFoundErrLevel); err1 != nil {
level = zap.ErrorLevel
}
}
l.Log(level, "sql trace", zap.String("sql", sql), zap.Float64("latency", latency), zap.Int64("rows", rows), zap.String("error", err.Error()))
case g.slowThreshold != 0 && latency > g.slowThreshold.Seconds():
l.Warn("sql trace[slow]", zap.String("sql", sql), zap.Float64("latency", latency), zap.Int64("rows", rows), zap.Float64("threshold", g.slowThreshold.Seconds()))
default:
l.Info("sql trace", zap.String("sql", sql), zap.Float64("latency", latency), zap.Int64("rows", rows))
}
}

//
// NewGormLogger

Check warning on line 132 in gorm.go

View workflow job for this annotation

GitHub Actions / Test on go 1.18 and ubuntu-latest

comment on exported function NewGormLogger should be of the form "NewGormLogger ..."

Check warning on line 132 in gorm.go

View workflow job for this annotation

GitHub Actions / Test on go 1.18 and ubuntu-latest

comment on exported function NewGormLogger should be of the form "NewGormLogger ..."
// @Description: 创建实现了 gorm logger interface 的 logger
// @param opt
// @return GormLogger
// @return error
//
// @Description: 创建实现了 gorm logger interface 的 logger
// @param opt
// @return GormLogger
// @return error
func NewGormLogger(opt GormLoggerOptions) (GormLogger, error) {
l := GormLogger{
name: GormLoggerName,
callerSkip: GormLoggerCallerSkip,
logLevel: opt.LogLevel,
slowThreshold: opt.SlowThreshold,
name: GormLoggerName,
callerSkip: GormLoggerCallerSkip,
logLevel: opt.LogLevel,
slowThreshold: opt.SlowThreshold,
recordNotFoundErrLevel: opt.RecordNotFoundErrLevel,
}
if opt.Name != "" {
l.name = opt.Name
Expand Down
80 changes: 43 additions & 37 deletions redis.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ package logit

import (
"context"
"errors"
"time"

"github.com/gin-gonic/gin"
Expand Down Expand Up @@ -49,6 +50,8 @@ type RedisLoggerOptions struct {
// 配置日志字段 key 的名称
// Optional.
EncoderConfig *zapcore.EncoderConfig
// nil err level
NilErrLevel string
}

type RedisLogger struct {

Check warning on line 57 in redis.go

View workflow job for this annotation

GitHub Actions / Test on go 1.18 and ubuntu-latest

exported type RedisLogger should have comment or be unexported
Expand All @@ -57,13 +60,15 @@ type RedisLogger struct {
slowThreshold time.Duration
callerSkip int
_logger *zap.Logger
nilErrLevel string
}

func NewRedisLogger(opt RedisLoggerOptions) (RedisLogger, error) {
l := RedisLogger{
name: defaultRedisLoggerName,
callerSkip: defaultRedisLoggerCallerSkip,
slowThreshold: defaultSlowThreshold,
nilErrLevel: opt.NilErrLevel,
}
if opt.CallerSkip != 0 {
l.callerSkip = opt.CallerSkip
Expand All @@ -88,27 +93,25 @@ func NewRedisLogger(opt RedisLoggerOptions) (RedisLogger, error) {
return l, err
}

//
// CtxLogger
// @Description: 创建打印日志的 ctx logger
// @receiver l
// @param ctx
// @return *zap.Logger
//
// @Description: 创建打印日志的 ctx logger
// @receiver l
// @param ctx
// @return *zap.Logger
func (l RedisLogger) CtxLogger(ctx context.Context) *zap.Logger {
_, ctxLogger := NewCtxLogger(ctx, l._logger, "")
return ctxLogger.WithOptions(zap.AddCallerSkip(l.callerSkip))
}

//
// BeforeProcess
// @Description: 实现 go-redis HOOK BeforeProcess 方法
// @receiver l
// @param ctx
// @param cmd
// @return context.Context
// @return error
//
// @Description: 实现 go-redis HOOK BeforeProcess 方法
// @receiver l
// @param ctx
// @param cmd
// @return context.Context
// @return error
func (l RedisLogger) BeforeProcess(ctx context.Context, cmd redis.Cmder) (context.Context, error) {

Check warning on line 115 in redis.go

View workflow job for this annotation

GitHub Actions / Test on go 1.18 and ubuntu-latest

parameter 'cmd' seems to be unused, consider removing or renaming it as _
if gc, ok := ctx.(*gin.Context); ok {
// set start time in gin.Context
Expand All @@ -119,19 +122,25 @@ func (l RedisLogger) BeforeProcess(ctx context.Context, cmd redis.Cmder) (contex
return context.WithValue(ctx, ctxRedisStartKey, time.Now()), nil
}

//
// AfterProcess
// @Description: 实现 go-redis HOOK AfterProcess 方法
// @receiver l
// @param ctx
// @param cmd
// @return error
//
// @Description: 实现 go-redis HOOK AfterProcess 方法
// @receiver l
// @param ctx
// @param cmd
// @return error
func (l RedisLogger) AfterProcess(ctx context.Context, cmd redis.Cmder) error {
logger := l.CtxLogger(ctx)
cost := l.getCost(ctx)
if err := cmd.Err(); err != nil {
logger.Error("redis trace", zap.String("command", cmd.FullName()), zap.String("args", cmd.String()), zap.Float64("latency_ms", cost), zap.Error(err))
level := zap.ErrorLevel
if errors.Is(err, redis.Nil) {
var err1 error
if level, err1 = zapcore.ParseLevel(l.nilErrLevel); err1 != nil {
level = zap.ErrorLevel
}
}
logger.Log(level, "redis trace", zap.String("command", cmd.FullName()), zap.String("args", cmd.String()), zap.Float64("latency_ms", cost), zap.Error(err))
} else {
log := logger.Info
if cost > float64(l.slowThreshold) {
Expand All @@ -142,15 +151,14 @@ func (l RedisLogger) AfterProcess(ctx context.Context, cmd redis.Cmder) error {
return nil
}

//
// BeforeProcessPipeline
// @Description:
// @receiver l
// @param ctx
// @param cmds
// @return context.Context
// @return error
//
// @Description:
// @receiver l
// @param ctx
// @param cmds
// @return context.Context
// @return error
func (l RedisLogger) BeforeProcessPipeline(ctx context.Context, cmds []redis.Cmder) (context.Context, error) {

Check warning on line 162 in redis.go

View workflow job for this annotation

GitHub Actions / Test on go 1.18 and ubuntu-latest

parameter 'cmds' seems to be unused, consider removing or renaming it as _
if gc, ok := ctx.(*gin.Context); ok {
// set start time in gin.Context
Expand All @@ -161,14 +169,13 @@ func (l RedisLogger) BeforeProcessPipeline(ctx context.Context, cmds []redis.Cmd
return context.WithValue(ctx, ctxRedisStartKey, time.Now()), nil
}

//
// AfterProcessPipeline
// @Description: 实现 go-redis HOOK AfterProcessPipeline 方法
// @receiver l
// @param ctx
// @param cmds
// @return error
//
// @Description: 实现 go-redis HOOK AfterProcessPipeline 方法
// @receiver l
// @param ctx
// @param cmds
// @return error
func (l RedisLogger) AfterProcessPipeline(ctx context.Context, cmds []redis.Cmder) error {
logger := l.CtxLogger(ctx)
cost := l.getCost(ctx)
Expand All @@ -188,13 +195,12 @@ func (l RedisLogger) AfterProcessPipeline(ctx context.Context, cmds []redis.Cmde
return nil
}

//
// getCost
// @Description: 获取命令执行耗时
// @receiver l
// @param ctx
// @return cost
//
// @Description: 获取命令执行耗时
// @receiver l
// @param ctx
// @return cost
func (l RedisLogger) getCost(ctx context.Context) (cost float64) {
var startTime time.Time
if gc, ok := ctx.(*gin.Context); ok {
Expand Down

0 comments on commit 90767a1

Please sign in to comment.