重构日志与可观测性体系
新增单行文本编码器与结构化 GORM 日志,统一错误记录与请求日志策略,收紧日志文件权限并修复按天切分与压缩,支付回调参数脱敏,生产强制阿里云短信,RequestID 校验防注入,日志文案中文化。
This commit is contained in:
@@ -3,12 +3,18 @@ package middleware
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
var requestIDFallbackCounter atomic.Uint64
|
||||
|
||||
const (
|
||||
RequestIDHeader = "X-Request-ID"
|
||||
ContextRequestID = "request_id"
|
||||
@@ -17,7 +23,7 @@ const (
|
||||
func RequestID() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
requestID := c.GetHeader(RequestIDHeader)
|
||||
if requestID == "" {
|
||||
if !validRequestID(requestID) {
|
||||
requestID = newRequestID()
|
||||
}
|
||||
c.Set(ContextRequestID, requestID)
|
||||
@@ -42,7 +48,19 @@ func GetRequestID(c *gin.Context) string {
|
||||
func newRequestID() string {
|
||||
buf := make([]byte, 16)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
return ""
|
||||
return fmt.Sprintf("%x-%x", time.Now().UnixNano(), requestIDFallbackCounter.Add(1))
|
||||
}
|
||||
return hex.EncodeToString(buf)
|
||||
}
|
||||
|
||||
func validRequestID(value string) bool {
|
||||
if value == "" || len(value) > 64 {
|
||||
return false
|
||||
}
|
||||
return strings.IndexFunc(value, func(char rune) bool {
|
||||
return !((char >= 'a' && char <= 'z') ||
|
||||
(char >= 'A' && char <= 'Z') ||
|
||||
(char >= '0' && char <= '9') ||
|
||||
char == '-' || char == '_' || char == '.')
|
||||
}) == -1
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user