gin_logger.go 831 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package fslog
  2. import (
  3. "bytes"
  4. ginzap "github.com/gin-contrib/zap"
  5. "github.com/gin-gonic/gin"
  6. "go.uber.org/zap"
  7. "go.uber.org/zap/zapcore"
  8. "io"
  9. "time"
  10. )
  11. func GinLogger() gin.HandlerFunc {
  12. lazyInitialize()
  13. return ginzap.GinzapWithConfig(logger, &ginzap.Config{
  14. UTC: true,
  15. TimeFormat: time.RFC3339,
  16. Context: func(c *gin.Context) []zapcore.Field {
  17. var body []byte
  18. var buf bytes.Buffer
  19. fields := make([]zapcore.Field, 0)
  20. body, err := io.ReadAll(c.Request.Body)
  21. if err != nil {
  22. return make([]zapcore.Field, 0)
  23. }
  24. if body != nil && len(body) != 0 {
  25. fields = append(fields, zap.String("body", string(body)))
  26. c.Request.Body = io.NopCloser(&buf)
  27. }
  28. return fields
  29. },
  30. })
  31. }
  32. func GinRecovery() gin.HandlerFunc {
  33. lazyInitialize()
  34. return ginzap.RecoveryWithZap(logger, true)
  35. }