提交 6c3a1bfa authored 作者: mooncake9527's avatar mooncake9527

record api cost

上级 7474de31
......@@ -18,6 +18,8 @@ const (
GinContextKey = "ginContext"
HeaderXTimestampKey = "Timestamp"
KeyReqBody = "reqBody"
KeyAppName = "appName"
KeyApiStartTime = "apiStartTime"
KeyRspBody = "rspBody"
KeyClientIP = "clientIP"
KeyUID = "userId"
......@@ -245,7 +247,7 @@ func AddApiCost(c *gin.Context, appName string, start time.Time) {
if cost == "" {
cost = currentCost
} else {
cost = fmt.Sprintf("%s,%s", cost, currentCost)
cost = fmt.Sprintf("%s,%s", currentCost, cost)
}
c.Writer.Header().Set(KeyCost, cost)
}
......
......@@ -196,6 +196,7 @@ func Logging(opts ...Option) gin.HandlerFunc {
copyHttpReq.Headers = c.Request.Header
copyHttpReq.Body = buf.String()
c.Set(ctxUtils.KeyReqBody, copyHttpReq)
c.Set(ctxUtils.KeyAppName, o.appName)
reqID := ""
if o.traceIDFrom == 1 {
......@@ -223,8 +224,6 @@ func Logging(opts ...Option) gin.HandlerFunc {
// processing requests
c.Next()
ctxUtils.AddApiCost(c, o.appName, start)
//print return message after processing
fields = []zap.Field{
zap.Int("code", c.Writer.Status()),
......
......@@ -2,13 +2,11 @@ package middleware
import (
"context"
"github.com/gin-gonic/gin"
ctxUtil "gitlab.wanzhuangkj.com/tush/xpkg/gin/ctxUtils"
"go.uber.org/zap"
"net/http"
"strconv"
"time"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
// RequestIDOption set the request id options.
......@@ -86,14 +84,15 @@ func RequestID(opts ...RequestIDOption) gin.HandlerFunc {
c.Request.Header.Set(ctxUtil.HeaderXRequestIDKey, requestID)
}
st := time.Now()
// Expose it for use in the application
c.Set(ctxUtil.ContextTraceIDKey, requestID)
c.Set(ctxUtil.KeyApiStartTime, st)
// Set X-Request-Id header
c.Writer.Header().Set(ctxUtil.HeaderXRequestIDKey, requestID)
c.Next()
c.Writer.Header().Set(ctxUtil.HeaderXTimestampKey, strconv.FormatInt(time.Now().Unix(), 10))
}
}
......
......@@ -5,6 +5,7 @@ import (
"encoding/json"
"gitlab.wanzhuangkj.com/tush/xpkg/gin/entity"
"net/http"
"strconv"
"time"
"github.com/gin-gonic/gin"
......@@ -145,6 +146,11 @@ func Out(c *gin.Context, err *errcode.Error, data ...interface{}) {
// status code flat 200, custom error codes in data.code
func respJSONWith200(c *gin.Context, code int, msg string, data ...interface{}) {
c.Writer.Header().Set(ctxUtils.HeaderXTimestampKey, strconv.FormatInt(time.Now().Unix(), 10))
appName := c.GetString(ctxUtils.KeyAppName)
stTime := c.GetTime(ctxUtils.KeyApiStartTime)
ctxUtils.AddApiCost(c, appName, stTime)
if len(data) > 0 {
writeJSON(c, http.StatusOK, newResp(c, code, msg, data[0]))
return
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论