优化日志记录并改用非 root 运行

This commit is contained in:
yml2213
2026-07-29 17:01:36 +08:00
parent e5309cdf23
commit c9d0803b53
10 changed files with 102 additions and 8 deletions
+27 -2
View File
@@ -2,6 +2,7 @@ package middleware
import (
"net/http"
"strings"
"time"
"hfb_sys/backend/pkg/response"
@@ -10,7 +11,7 @@ import (
"go.uber.org/zap"
)
// 正常请求不记录访问日志;只有慢请求、服务端错误、限流和有诊断价值的认证失败会输出。
// 查询请求默认静默;成功写操作、慢请求、服务端错误、限流和有诊断价值的认证失败会输出。
const slowRequestThresholdMs = 500
func RequestLogger(logger *zap.Logger) gin.HandlerFunc {
@@ -23,8 +24,9 @@ func RequestLogger(logger *zap.Logger) gin.HandlerFunc {
path := c.Request.URL.Path
route := c.FullPath()
authFailure := meaningfulAuthFailure(c)
operation := meaningfulOperation(c.Request.Method, path, status)
if shouldSkipHTTPLog(path, route, status, latencyMs) && !authFailure {
if shouldSkipHTTPLog(path, route, status, latencyMs) && !authFailure && !operation {
return
}
@@ -78,10 +80,33 @@ func RequestLogger(logger *zap.Logger) gin.HandlerFunc {
logger.Warn("后台认证失败", fields...)
case latencyMs >= slowRequestThresholdMs:
logger.Warn("HTTP 慢请求", fields...)
case operation:
logger.Info("HTTP 操作完成", fields...)
}
}
}
func meaningfulOperation(method, path string, status int) bool {
if status < 200 || status >= 400 {
return false
}
// 支付回调已有更完整的业务结果日志,不再重复记录一条访问日志。
if isPaymentNotifyPath(path) {
return false
}
switch method {
case http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete:
return true
default:
return false
}
}
func isPaymentNotifyPath(path string) bool {
return (strings.Contains(path, "/payment/") || strings.Contains(path, "/payments/")) &&
strings.HasSuffix(strings.TrimSuffix(path, "/"), "/notify")
}
// shouldSkipHTTPLog 判断是否为无需记录的普通请求。
func shouldSkipHTTPLog(_, _ string, status int, latencyMs float64) bool {
if status >= 500 || status == http.StatusTooManyRequests {