1 Star 0 Fork 0

piecat / summer

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
Logger.go 1.52 KB
一键复制 编辑 原始数据 按行查看 历史
why2go 提交于 2022-08-07 18:57 . update
package logger
import (
"crypto/rand"
"encoding/hex"
"time"
"github.com/gin-gonic/gin"
"github.com/rs/zerolog/log"
)
var (
logger = log.With().Str("ltag", "ginLogger").Logger()
)
type LoggerConfig struct {
SkipPaths []string
}
// LoggerWithConfig instance a Logger middleware with config.
func LoggerWithConfig(conf LoggerConfig) gin.HandlerFunc {
notlogged := conf.SkipPaths
var skip map[string]struct{}
if length := len(notlogged); length > 0 {
skip = make(map[string]struct{}, length)
for _, path := range notlogged {
skip[path] = struct{}{}
}
}
return func(c *gin.Context) {
// Start timer
start := time.Now()
path := c.Request.URL.Path
raw := c.Request.URL.RawQuery
requestId := genRequestId()
if len(raw) != 0 {
path = path + "?" + raw
}
_, skipped := skip[path]
c.Request.Header.Add("requestId", requestId)
// Process request
c.Next()
// Log only when path is not being skipped
if !skipped {
if len(raw) != 0 {
path = path + "?" + raw
}
logger.Log().
Str("peer", c.ClientIP()).
Str("method", c.Request.Method).
Str("path", path).
Str("requestId", requestId).
Int("statusCode", c.Writer.Status()).
Dur("latency", time.Since(start)).
Int("bodySize", c.Writer.Size()).
Str("errMsg", c.Errors.ByType(gin.ErrorTypePrivate).String()).
Send()
}
}
}
func genRequestId() string {
buf := make([]byte, 16)
_, err := rand.Read(buf)
if err != nil {
logger.Fatal().Err(err).Msg("generate request id failed")
}
return hex.EncodeToString(buf)
}
Go
1
https://gitee.com/piecat/summer.git
git@gitee.com:piecat/summer.git
piecat
summer
summer
ginstarter/v0.0.16

搜索帮助