1 Star 0 Fork 0

tfhappy/tools

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
logger.go 1.87 KB
一键复制 编辑 原始数据 按行查看 历史
tfhappy 提交于 2021-04-15 19:59 +08:00 . remove: middleware config
package middleware
import (
"bytes"
"io/ioutil"
"time"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
)
type responseBodyWriter struct {
gin.ResponseWriter
body *bytes.Buffer
}
func (w responseBodyWriter) Write(b []byte) (int, error) {
w.body.Write(b)
return w.ResponseWriter.Write(b)
}
func (w responseBodyWriter) WriteString(s string) (int, error) {
w.body.WriteString(s)
return w.ResponseWriter.WriteString(s)
}
type LoggerField map[string]func(*gin.Context) string
// Logger use for gin middleware
func Logger(fields ...LoggerField) func(*gin.Context) {
return func(c *gin.Context) {
startTime := time.Now()
body, _ := c.GetRawData()
c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(body)) // 重写回body
// wrap gin.ResponseWriter
w := &responseBodyWriter{body: &bytes.Buffer{}, ResponseWriter: c.Writer}
c.Writer = w
c.Next()
cost := time.Since(startTime)
log := logrus.WithFields(logrus.Fields{
"cost_string": cost.String(),
"cost": cost.Milliseconds(),
"error": c.Errors.String(),
"client_ip": c.ClientIP(),
"req_uri": c.Request.RequestURI,
"req_method": c.Request.Method,
"host": c.Request.Host,
"request_referer": c.Request.Referer(),
"req_body": string(body),
"response": w.body.String(),
})
for _, field := range fields {
for key, gValue := range field {
log.WithField(key, gValue(c))
}
}
if c.Errors.String() == "" {
log.Info()
} else {
log.Error()
}
}
}
func GetUserIDField(userIDKey string) LoggerField {
return WarpContextField(userIDKey, "user")
}
func GetTokenField(tokenKey string) LoggerField {
return WarpContextField(tokenKey, "access_token")
}
func WarpContextField(contextKey, key string) LoggerField {
gv := func(c *gin.Context) string {
return c.GetString(contextKey)
}
return LoggerField{key: gv}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/tfhappy/tools.git
git@gitee.com:tfhappy/tools.git
tfhappy
tools
tools
0b2cb5f0de5a

搜索帮助