抽取 Gin、配置、日志、数据库、Redis 与出站 HTTP 基础能力。 新增统一接入指南,将能力清单和相对链接检查纳入 make verify。 对齐远端 module 路径,修正 Redis 读写超时特殊值映射。 验证:make verify、make race-check 均通过。
This commit is contained in:
commit
b4c3ac622c
55 files changed
+5862
No files matched your search
@@ -0,0 +1,79 @@
|
||||
package logger
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"git.zhangdeman.cn/github/ginframework/diagnostic"
|
||||
"git.zhangdeman.cn/github/ginframework/logger/storagevalue"
|
||||
"go.uber.org/zap"
|
||||
"go.uber.org/zap/zapcore"
|
||||
)
|
||||
|
||||
var (
|
||||
startupLogger = zap.New(zapcore.NewCore(zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()), zapcore.Lock(os.Stderr), zapcore.ErrorLevel))
|
||||
)
|
||||
|
||||
// RecordError 通过 default 命名输出记录错误;初始化前使用标准错误输出。
|
||||
// 入参:message 为调用处安全英文摘要,err 为需要保留的原因链。
|
||||
// 隐式逻辑:不输出原始错误文本,避免驱动错误携带 SQL、凭据或正文。
|
||||
func RecordError(message string, err error) {
|
||||
RecordErrorContext(context.Background(), message, err)
|
||||
}
|
||||
|
||||
// RecordErrorContext 记录带可信调用诊断的错误,不从请求头或正文推导链路字段。
|
||||
// 入参:ctx 为标准上下文,message 为安全英文摘要,err 为原始错误链。
|
||||
// 隐式逻辑:与 RecordError 使用同一命名输出,不建立第二套日志器。
|
||||
func RecordErrorContext(ctx context.Context, message string, err error) {
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
outputMutex.RLock()
|
||||
item, exists := outputs["default"]
|
||||
outputMutex.RUnlock()
|
||||
instance := startupLogger
|
||||
if exists {
|
||||
instance = item.logger
|
||||
}
|
||||
var (
|
||||
coded interface{ Code() int }
|
||||
code int
|
||||
)
|
||||
if errors.As(err, &coded) {
|
||||
code = coded.Code()
|
||||
}
|
||||
snapshot := diagnostic.From(ctx)
|
||||
instance.Error(message, zap.Int("error_code", code), zap.Any("cause_chain", errorChain(err, 0)),
|
||||
zap.String("trace_id", snapshot.TraceID), zap.String("request_id", snapshot.RequestID), zap.String("uri", snapshot.URI))
|
||||
}
|
||||
|
||||
// Fields 生成附加数据的脱敏字段,不让调用方覆盖可信诊断字段。
|
||||
// 入参:data 为任意结构化日志载荷。
|
||||
// 返回:独立的脱敏日志副本。
|
||||
func Fields(data any) zap.Field { return zap.Any("data", storagevalue.Safe(data)) }
|
||||
|
||||
// errorChain 复制错误类型与数字码,保留多原因链的结构。
|
||||
// 入参:err 为原始错误,depth 为当前递归层级。
|
||||
// 返回:不包含原始错误文本的诊断树。
|
||||
func errorChain(err error, depth int) any {
|
||||
if err == nil || depth >= 16 {
|
||||
return nil
|
||||
}
|
||||
result := map[string]any{"type": fmt.Sprintf("%T", err)}
|
||||
if coded, ok := err.(interface{ Code() int }); ok {
|
||||
result["code"] = coded.Code()
|
||||
}
|
||||
switch value := err.(type) {
|
||||
case interface{ Unwrap() []error }:
|
||||
children := make([]any, 0, len(value.Unwrap()))
|
||||
for _, child := range value.Unwrap() {
|
||||
children = append(children, errorChain(child, depth+1))
|
||||
}
|
||||
result["causes"] = children
|
||||
case interface{ Unwrap() error }:
|
||||
result["cause"] = errorChain(value.Unwrap(), depth+1)
|
||||
}
|
||||
return result
|
||||
}
|
||||