代码拉取完成,页面将自动刷新
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)
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。