支持设置日志扩展字段

This commit is contained in:
白茶清欢 2024-06-21 18:48:06 +08:00
parent 9daae92046
commit c315db9a8a
2 changed files with 15 additions and 4 deletions

View File

@ -25,7 +25,7 @@ type IRedisClient interface {
GetRealClientWithError(instanceFlag string) (*redis.Client, error) // 获取带error的客户端连接
AddClient(instanceFlag string, instanceConfig *define.Options) error // 添加新的客户端连接
RemoveClient(instanceFlag string) // 移除一个客户端连接
SetLogger(loggerInstance *zap.Logger) // 设置日志实例, 全局生效, 而非针对某一个实例
SetLogger(loggerInstance *zap.Logger, extraLogFieldList []string) // 设置日志实例, 全局生效, 而非针对某一个实例
Exec(ctx context.Context, instanceFlag string, command string, args ...any) *define.RedisResult // 执行任意命令
SetCommandWhiteList(command []string) // 设置命令的白名单,全局生效, 而非单独针对某一个实例
}

View File

@ -38,6 +38,7 @@ type OwnClient struct {
instanceTable map[string]*redisClient.Client
whiteCommandTable map[string]bool
logger *zap.Logger
extraLogFieldList []string
}
func (o *OwnClient) isAllowCommand(command string) bool {
@ -61,6 +62,9 @@ func (o *OwnClient) isAllowCommand(command string) bool {
//
// Date : 11:05 2024/6/19
func (o *OwnClient) Exec(ctx context.Context, instanceFlag string, command string, args ...any) *define.RedisResult {
if nil == ctx {
ctx = context.Background()
}
var (
instance *redisClient.Client
)
@ -90,8 +94,7 @@ func (o *OwnClient) Exec(ctx context.Context, instanceFlag string, command strin
// 未注入日志实例
return
}
o.logger.Info(
"Redis命令执行记录",
logDataList := []zap.Field{
zap.Int64("start_time", res.StartTime),
zap.Int64("finish_time", res.FinishTime),
zap.Int64("used_time", res.UsedTime),
@ -99,6 +102,13 @@ func (o *OwnClient) Exec(ctx context.Context, instanceFlag string, command strin
zap.String("arg_list", strings.Join(res.ArgList, " ")),
zap.String("execute_result", res.Result),
zap.Error(res.Err),
}
for _, item := range o.extraLogFieldList {
logDataList = append(logDataList, zap.Any(item, ctx.Value(item)))
}
o.logger.Info(
"Redis命令执行记录",
logDataList...,
)
}()
if instance, res.Err = o.GetRealClientWithError(instanceFlag); nil != res.Err {
@ -189,6 +199,7 @@ func (o *OwnClient) RemoveClient(instanceFlag string) {
delete(o.instanceTable, instanceFlag)
}
func (o *OwnClient) SetLogger(loggerInstance *zap.Logger) {
func (o *OwnClient) SetLogger(loggerInstance *zap.Logger, extraLogFieldList []string) {
o.logger = loggerInstance
o.extraLogFieldList = extraLogFieldList
}