logger/util.go
2024-07-24 23:05:55 +08:00

84 lines
2.1 KiB
Go

// Package logger ...
//
// Description : logger ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2024-07-24 21:14
package logger
import (
"context"
"fmt"
"os"
"github.com/gin-gonic/gin"
ginRequest "git.zhangdeman.cn/zhangdeman/gin/request"
"git.zhangdeman.cn/zhangdeman/network/util"
"git.zhangdeman.cn/zhangdeman/serialize"
"go.uber.org/zap"
)
func getStrVal(ctx context.Context, key string) string {
if nil == ctx {
return ""
}
if ginCtx, ok := ctx.(*gin.Context); ok {
return ginRequest.WrapperHandle.GetCtxStringData(ginCtx, key, "")
}
val := ctx.Value(key)
if nil == val {
return ""
}
return fmt.Sprintf("%v", val)
}
// NewLogData ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 16:21 2024/7/23
func NewLogData(ctx context.Context, logType string, code string, logData map[string]any) *LogData {
hostname, _ := os.Hostname()
commonLogData := &LogData{
Env: getStrVal(ctx, "env"),
Uri: getStrVal(ctx, "uri"),
TraceID: getStrVal(ctx, "trace_id"),
UserID: getStrVal(ctx, "user_id"),
UserRoleID: getStrVal(ctx, "user_role_id"),
OperateMode: getStrVal(ctx, "operate_mode"),
LogType: logType,
CodeVersion: getStrVal(ctx, "code_version"),
ServiceVersion: getStrVal(ctx, "service_version"),
ClientIp: getStrVal(ctx, "client_ip"),
ServerIp: util.IP.GetHostIP(),
Hostname: hostname,
Code: code,
Data: logData,
}
return commonLogData
}
// ZapLogDataList 记录的日志数据字段列表
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 17:33 2024/7/23
func ZapLogDataList(logData *LogData) []zap.Field {
logDataList := make([]zap.Field, 0)
if logData == nil {
return logDataList
}
var mapData map[string]any
_ = serialize.JSON.Transition(logData, &mapData)
delete(mapData, "data") // data字段单独展开
for k, v := range mapData {
logDataList = append(logDataList, zap.Any(k, v))
}
for k, v := range logData.Data { // 展开一层数据属性
logDataList = append(logDataList, zap.Any("data_"+k, v))
}
return logDataList
}