重构日志与可观测性体系
新增单行文本编码器与结构化 GORM 日志,统一错误记录与请求日志策略,收紧日志文件权限并修复按天切分与压缩,支付回调参数脱敏,生产强制阿里云短信,RequestID 校验防注入,日志文案中文化。
This commit is contained in:
@@ -1,11 +1,15 @@
|
||||
package response
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const contextResponseCode = "response_code"
|
||||
|
||||
type Body struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
@@ -29,12 +33,39 @@ func Created(c *gin.Context, data any) {
|
||||
}
|
||||
|
||||
func Error(c *gin.Context, status int, code, message string) {
|
||||
if status >= http.StatusInternalServerError && len(c.Errors) == 0 {
|
||||
RecordError(c, fmt.Errorf("未记录原始错误: %s", code))
|
||||
}
|
||||
c.Set(contextResponseCode, code)
|
||||
c.JSON(status, Body{
|
||||
Code: code,
|
||||
Message: message,
|
||||
})
|
||||
}
|
||||
|
||||
// RecordError 保存原始错误,供统一请求日志记录服务端故障原因。
|
||||
func RecordError(c *gin.Context, err error) {
|
||||
if c == nil || err == nil {
|
||||
return
|
||||
}
|
||||
for _, item := range c.Errors {
|
||||
if errors.Is(item.Err, err) {
|
||||
return
|
||||
}
|
||||
}
|
||||
_ = c.Error(err)
|
||||
}
|
||||
|
||||
// CodeFromContext 返回已经写入响应的稳定业务错误码。
|
||||
func CodeFromContext(c *gin.Context) string {
|
||||
value, ok := c.Get(contextResponseCode)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
code, _ := value.(string)
|
||||
return code
|
||||
}
|
||||
|
||||
func BadRequest(c *gin.Context, message string) {
|
||||
Error(c, http.StatusBadRequest, "bad_request", message)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user