2024-07-24 21:41:07 +08:00
|
|
|
// Package logger ...
|
|
|
|
//
|
|
|
|
// Description : logger ...
|
|
|
|
//
|
|
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
|
|
//
|
|
|
|
// Date : 2024-07-24 21:14
|
|
|
|
package logger
|
|
|
|
|
|
|
|
import (
|
2024-07-24 22:43:09 +08:00
|
|
|
"context"
|
|
|
|
"fmt"
|
2024-07-24 21:41:07 +08:00
|
|
|
"os"
|
|
|
|
|
2024-07-24 22:43:09 +08:00
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
|
|
|
|
ginRequest "git.zhangdeman.cn/zhangdeman/gin/request"
|
2024-07-24 21:41:07 +08:00
|
|
|
"git.zhangdeman.cn/zhangdeman/network/util"
|
|
|
|
"git.zhangdeman.cn/zhangdeman/serialize"
|
|
|
|
"go.uber.org/zap"
|
|
|
|
)
|
|
|
|
|
2024-07-24 22:43:09 +08:00
|
|
|
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)
|
|
|
|
}
|
|
|
|
|
2024-07-24 21:41:07 +08:00
|
|
|
// NewLogData ...
|
|
|
|
//
|
|
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
|
|
//
|
|
|
|
// Date : 16:21 2024/7/23
|
2024-07-24 22:43:09 +08:00
|
|
|
func NewLogData(ctx context.Context, logType string, code string, logData map[string]any) *LogData {
|
2024-07-24 21:41:07 +08:00
|
|
|
hostname, _ := os.Hostname()
|
|
|
|
commonLogData := &LogData{
|
2024-07-24 23:05:55 +08:00
|
|
|
Env: getStrVal(ctx, "env"),
|
2024-07-24 22:43:09 +08:00
|
|
|
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"),
|
2024-07-24 21:41:07 +08:00
|
|
|
LogType: logType,
|
2024-07-24 22:43:09 +08:00
|
|
|
CodeVersion: getStrVal(ctx, "code_version"),
|
|
|
|
ServiceVersion: getStrVal(ctx, "service_version"),
|
|
|
|
ClientIp: getStrVal(ctx, "client_ip"),
|
2024-07-24 21:41:07 +08:00
|
|
|
ServerIp: util.IP.GetHostIP(),
|
|
|
|
Hostname: hostname,
|
|
|
|
Code: code,
|
|
|
|
Data: logData,
|
|
|
|
}
|
|
|
|
return commonLogData
|
|
|
|
}
|
|
|
|
|
|
|
|
// ZapLogDataList 记录的日志数据字段列表
|
|
|
|
//
|
|
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
|
|
//
|
|
|
|
// Date : 17:33 2024/7/23
|
2024-07-24 22:03:22 +08:00
|
|
|
func ZapLogDataList(logData *LogData) []zap.Field {
|
2024-07-24 21:41:07 +08:00
|
|
|
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
|
|
|
|
}
|