Files
Yi Caiandseefs001 30748c6558 fix(logging): 隐藏访问日志中的查询凭据 (#7972)
* fix(logging): 隐藏访问日志中的查询凭据

* fix(logging): redact query credentials in access logs

---------

Co-authored-by: seefs001 <i@seefs.me>
2026-10-23 13:31:23 +08:00

53 lines
1.4 KiB
Go

package middleware
import (
"fmt"
"strings"
"github.com/QuantumNous/new-api/common"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/gin-gonic/gin"
)
const RouteTagKey = "route_tag"
func RouteTag(tag string) gin.HandlerFunc {
return func(c *gin.Context) {
c.Set(RouteTagKey, tag)
c.Next()
}
}
func SetUpLogger(server *gin.Engine) {
server.Use(redactTaskArtifactAccessQuery())
server.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {
var requestID string
if param.Keys != nil {
requestID, _ = param.Keys[common.RequestIdKey].(string)
}
tag, _ := param.Keys[RouteTagKey].(string)
if tag == "" {
tag = "web"
}
path := param.Path
// OAuth callbacks carry one-time codes and state in the query string.
// Redact the log value only; the handler still needs the original query.
if strings.HasPrefix(path, "/api/oauth/") || strings.HasPrefix(path, "/oauth/") {
path, _, _ = strings.Cut(path, "?")
} else if param.Request.URL.RawQuery != "" {
query := param.Request.URL.Query().Encode()
path = param.Request.URL.EscapedPath() + relaycommon.SanitizeURLForLog("?"+query)
}
return fmt.Sprintf("[GIN] %s | %s | %s | %3d | %13v | %15s | %7s %s\n",
param.TimeStamp.Format("2006/01/02 - 15:04:05"),
tag,
requestID,
param.StatusCode,
param.Latency,
param.ClientIP,
param.Method,
path,
)
}))
}