logger.go 820 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package middleware
  2. import (
  3. "fmt"
  4. "github.com/QuantumNous/new-api/common"
  5. "github.com/gin-gonic/gin"
  6. )
  7. const RouteTagKey = "route_tag"
  8. func RouteTag(tag string) gin.HandlerFunc {
  9. return func(c *gin.Context) {
  10. c.Set(RouteTagKey, tag)
  11. c.Next()
  12. }
  13. }
  14. func SetUpLogger(server *gin.Engine) {
  15. server.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {
  16. var requestID string
  17. if param.Keys != nil {
  18. requestID, _ = param.Keys[common.RequestIdKey].(string)
  19. }
  20. tag, _ := param.Keys[RouteTagKey].(string)
  21. if tag == "" {
  22. tag = "web"
  23. }
  24. return fmt.Sprintf("[GIN] %s | %s | %s | %3d | %13v | %15s | %7s %s\n",
  25. param.TimeStamp.Format("2006/01/02 - 15:04:05"),
  26. tag,
  27. requestID,
  28. param.StatusCode,
  29. param.Latency,
  30. param.ClientIP,
  31. param.Method,
  32. param.Path,
  33. )
  34. }))
  35. }