基于 `zap` 包封装。除了实现 `Go` 日志包的基本功能外,还实现了很多高级功能 本包基于`github.com/tkestack/tke/pkg/util/log`裁剪
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

47 lines
1.1 KiB

2 years ago
  1. package ginLog
  2. import (
  3. "cynking.com/pkg/log"
  4. "github.com/gin-gonic/gin"
  5. "time"
  6. )
  7. func NamedLogger(msg string) gin.HandlerFunc {
  8. return func(c *gin.Context) {
  9. // Start timer
  10. start := time.Now()
  11. path := c.Request.URL.Path
  12. raw := c.Request.URL.RawQuery
  13. // Process request
  14. c.Next()
  15. param := gin.LogFormatterParams{
  16. Request: c.Request,
  17. Keys: c.Keys,
  18. }
  19. // Stop timer
  20. param.TimeStamp = time.Now()
  21. param.Latency = param.TimeStamp.Sub(start)
  22. param.ClientIP = c.ClientIP()
  23. param.Method = c.Request.Method
  24. param.StatusCode = c.Writer.Status()
  25. param.ErrorMessage = c.Errors.ByType(gin.ErrorTypePrivate).String()
  26. param.BodySize = c.Writer.Size()
  27. if raw != "" {
  28. path = path + "?" + raw
  29. }
  30. param.Path = path
  31. // todo:请求处理过长时间提升日志等级 debug(正常),info(慢速),warn(可能浏览器已判定超时)处理
  32. log.Debug(msg,
  33. log.Int("Status", param.StatusCode),
  34. log.Duration("Latency", param.Latency),
  35. log.String("Ip", param.ClientIP),
  36. log.String("Method", param.Method),
  37. log.String("Path", param.Path),
  38. log.String("ErrorMessage", param.ErrorMessage))
  39. }
  40. }