logger.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package hieda_ginutil
  2. import (
  3. "fmt"
  4. "git.swzry.com/zry/GoHiedaLogger/hiedalog"
  5. "github.com/gin-gonic/gin"
  6. "strconv"
  7. "time"
  8. )
  9. type GinLoggerConfig struct {
  10. Logger *hiedalog.HiedaLogger
  11. ModuleName string
  12. LevelMapFunc func(int) string
  13. }
  14. func GinLoggerWithStringLogger(config GinLoggerConfig) gin.HandlerFunc {
  15. return func(c *gin.Context) {
  16. start := time.Now()
  17. path := c.Request.URL.Path
  18. raw := c.Request.URL.RawQuery
  19. c.Next()
  20. end := time.Now()
  21. latency := end.Sub(start).String()
  22. clientIP := c.ClientIP()
  23. method := c.Request.Method
  24. statusCode := c.Writer.Status()
  25. lvs := config.LevelMapFunc(statusCode)
  26. // comment := c.Errors.ByType(gin.ErrorTypePrivate).String()
  27. if raw != "" {
  28. path = path + "?" + raw
  29. }
  30. sv := fmt.Sprintf("%v | %3d | %13v | %15s | %-7s %s",
  31. end.Format("2006/01/02 - 15:04:05"),
  32. statusCode,
  33. latency,
  34. clientIP,
  35. method,
  36. path,
  37. )
  38. config.Logger.LogString(config.ModuleName, lvs, sv)
  39. }
  40. }
  41. func GinLoggerWithComplexLogger(config GinLoggerConfig) gin.HandlerFunc {
  42. return func(c *gin.Context) {
  43. start := time.Now()
  44. path := c.Request.URL.Path
  45. raw := c.Request.URL.RawQuery
  46. c.Next()
  47. end := time.Now()
  48. latency := end.Sub(start).String()
  49. clientIP := c.ClientIP()
  50. method := c.Request.Method
  51. statusCode := c.Writer.Status()
  52. lvs := config.LevelMapFunc(statusCode)
  53. comment := c.Errors.ByType(gin.ErrorTypePrivate).String()
  54. if raw != "" {
  55. path = path + "?" + raw
  56. }
  57. mv := map[string]string{
  58. "time": end.Format("2006/01/02 - 15:04:05"),
  59. "status": strconv.Itoa(statusCode),
  60. "latency": latency,
  61. "clientIP": clientIP,
  62. "method": method,
  63. "path": path,
  64. "comment": comment,
  65. }
  66. config.Logger.LogComplex(config.ModuleName, lvs, mv)
  67. }
  68. }
  69. func GetSimpleLevelMapFunc(Http1xx, Http2xx, Http3xx, Http4xx, Http5xx, Default string) func(int) string {
  70. return func(code int) string {
  71. switch {
  72. case code >= 100 && code < 200:
  73. return Http1xx
  74. case code >= 200 && code < 300:
  75. return Http2xx
  76. case code >= 300 && code < 400:
  77. return Http3xx
  78. case code >= 400 && code < 500:
  79. return Http4xx
  80. case code >= 500 && code < 600:
  81. return Http5xx
  82. default:
  83. return Default
  84. }
  85. }
  86. }
  87. func GetDefaultLevelMapFunc() func(int) string {
  88. return GetSimpleLevelMapFunc(hiedalog.DLN_INFO, hiedalog.DLN_INFO, hiedalog.DLN_INFO, hiedalog.DLN_WARN, hiedalog.DLN_ERROR, hiedalog.DLN_ERROR)
  89. }