gin.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package common
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "sync"
  7. "time"
  8. "github.com/gin-gonic/gin"
  9. "github.com/sirupsen/logrus"
  10. )
  11. var fieldsPool = sync.Pool{
  12. New: func() any {
  13. return make(logrus.Fields, 6)
  14. },
  15. }
  16. func GetLogFields() logrus.Fields {
  17. fields, ok := fieldsPool.Get().(logrus.Fields)
  18. if !ok {
  19. panic(fmt.Sprintf("fields pool type error: %T, %v", fields, fields))
  20. }
  21. return fields
  22. }
  23. func PutLogFields(fields logrus.Fields) {
  24. clear(fields)
  25. fieldsPool.Put(fields)
  26. }
  27. func GetLogger(c *gin.Context) *logrus.Entry {
  28. return GetLoggerFromReq(c.Request)
  29. }
  30. type ginLoggerKey struct{}
  31. func GetLoggerFromReq(req *http.Request) *logrus.Entry {
  32. ctx := req.Context()
  33. if log := ctx.Value(ginLoggerKey{}); log != nil {
  34. v, ok := log.(*logrus.Entry)
  35. if !ok {
  36. panic(fmt.Sprintf("log type error: %T, %v", v, v))
  37. }
  38. return v
  39. }
  40. entry := NewLogger()
  41. SetLogger(req, entry)
  42. return entry
  43. }
  44. func SetLogger(req *http.Request, entry *logrus.Entry) {
  45. newCtx := context.WithValue(req.Context(), ginLoggerKey{}, entry)
  46. *req = *req.WithContext(newCtx)
  47. }
  48. func NewLogger() *logrus.Entry {
  49. return &logrus.Entry{
  50. Logger: logrus.StandardLogger(),
  51. Data: GetLogFields(),
  52. }
  53. }
  54. func TruncateDuration(d time.Duration) time.Duration {
  55. if d > time.Hour {
  56. return d.Truncate(time.Minute)
  57. }
  58. if d > time.Minute {
  59. return d.Truncate(time.Second)
  60. }
  61. if d > time.Second {
  62. return d.Truncate(time.Millisecond)
  63. }
  64. if d > time.Millisecond {
  65. return d.Truncate(time.Microsecond)
  66. }
  67. return d
  68. }