提交 476975d0 authored 作者: mooncake9527's avatar mooncake9527

打印请求响应报文时,可以限制输出日志的长度

上级 8fc3104f
...@@ -40,6 +40,7 @@ const ( ...@@ -40,6 +40,7 @@ const (
KeyUName CtxKey = "uname" KeyUName CtxKey = "uname"
KeyToken CtxKey = "token" KeyToken CtxKey = "token"
KeyCost CtxKey = "X-Request-Cost" KeyCost CtxKey = "X-Request-Cost"
KeyRspBodyMax CtxKey = "rsp-body-max"
) )
var ( var (
...@@ -55,6 +56,12 @@ func Set(c *gin.Context, key CtxKey, val any) { ...@@ -55,6 +56,12 @@ func Set(c *gin.Context, key CtxKey, val any) {
c.Set(key.String(), val) c.Set(key.String(), val)
} }
func SetRspBodyMax(ctx context.Context, max int) {
if c, _ := ToGinCtx(ctx); c != nil {
Set(c, KeyRspBodyMax, max)
}
}
func Get[T any](c *gin.Context, key CtxKey) (T, bool) { func Get[T any](c *gin.Context, key CtxKey) (T, bool) {
if val, ok := c.Get(key.String()); ok { if val, ok := c.Get(key.String()); ok {
if v, ok1 := val.(T); ok1 { if v, ok1 := val.(T); ok1 {
......
...@@ -233,6 +233,7 @@ func Logging(opts ...Option) gin.HandlerFunc { ...@@ -233,6 +233,7 @@ func Logging(opts ...Option) gin.HandlerFunc {
// processing requests // processing requests
c.Next() c.Next()
rspBodyMax := c.GetInt(ctxUtils.KeyRspBodyMax.String())
contentType := c.Writer.Header().Get("Content-Type") contentType := c.Writer.Header().Get("Content-Type")
isMedia := false isMedia := false
if strings.Contains(contentType, "image") { if strings.Contains(contentType, "image") {
...@@ -251,7 +252,11 @@ func Logging(opts ...Option) gin.HandlerFunc { ...@@ -251,7 +252,11 @@ func Logging(opts ...Option) gin.HandlerFunc {
if isMedia { if isMedia {
fields = append(fields, zap.ByteString("body", getResponseBody(newWriter.body, o.mediaMaxLength))) fields = append(fields, zap.ByteString("body", getResponseBody(newWriter.body, o.mediaMaxLength)))
} else { } else {
fields = append(fields, zap.ByteString("body", getResponseBody(newWriter.body, o.maxLength))) if rspBodyMax > 0 {
fields = append(fields, zap.ByteString("body", getResponseBody(newWriter.body, rspBodyMax)))
} else {
fields = append(fields, zap.ByteString("body", getResponseBody(newWriter.body, o.maxLength)))
}
} }
if reqID != "" { if reqID != "" {
fields = append(fields, zap.String(ctxUtils.ContextTraceIDKey.String(), reqID)) fields = append(fields, zap.String(ctxUtils.ContextTraceIDKey.String(), reqID))
......
package httpContentType
import (
"net/http"
"strings"
)
func IsMedia(header http.Header) bool {
ct := header.Get("Content-Type")
isMedia := false
if strings.Contains(ct, "image") {
isMedia = true
}
return isMedia
}
...@@ -8,6 +8,7 @@ import ( ...@@ -8,6 +8,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"gitlab.wanzhuangkj.com/tush/xpkg/httpcli/entity" "gitlab.wanzhuangkj.com/tush/xpkg/httpcli/entity"
"gitlab.wanzhuangkj.com/tush/xpkg/httpcli/httpContentType"
"io" "io"
"net/http" "net/http"
"net/url" "net/url"
...@@ -297,15 +298,54 @@ func (x *Request) send(ctx context.Context) { ...@@ -297,15 +298,54 @@ func (x *Request) send(ctx context.Context) {
x.pushDo(ctx) x.pushDo(ctx)
} }
body := x.RespBodyString()
if httpContentType.IsMedia(x.response.Header) {
body = string(getResponseBody(x.Response().BodyBuf(), 16))
}
logger.Info("[httpCli] rsp", logger.Info("[httpCli] rsp",
logger.String("cost", time.Since(st).String()), logger.String("cost", time.Since(st).String()),
logger.Int("statusCode", x.response.StatusCode), logger.Int("statusCode", x.response.StatusCode),
logger.String("status", x.response.Status), logger.String("status", x.response.Status),
logger.Any("header", x.Response().Header), logger.Any("header", x.Response().Header),
logger.String("body", x.RespBodyString()), logger.String("body", body),
ctxUtils.CtxTraceIDField(ctx)) ctxUtils.CtxTraceIDField(ctx))
} }
// If there is sensitive information in the body, you can use WithIgnoreRoutes set the route to ignore logging
func getResponseBody(buf *bytes.Buffer, maxLen int) []byte {
l := buf.Len()
if l == 0 {
return []byte("")
} else if l > maxLen {
l = maxLen
}
body := make([]byte, l)
n, _ := buf.Read(body)
if n == 0 {
return emptyBody
} else if n < maxLen {
if isLastByteNewline(body) {
return body[:n-1]
}
return body[:n]
}
return append(body[:maxLen-len(contentMark)], contentMark...)
}
var (
emptyBody = []byte("")
contentMark = []byte(" ...... ")
)
func isLastByteNewline(data []byte) bool {
if len(data) == 0 {
return false
}
return data[len(data)-1] == '\n'
}
func (x *Request) pushDo(ctx context.Context) { func (x *Request) pushDo(ctx context.Context) {
client := x.cli client := x.cli
if client == nil { if client == nil {
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论