request_logger.go 988 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package api
  2. import (
  3. "strings"
  4. "github.com/gin-gonic/gin"
  5. "gogs.baozhida.cn/zoie/OAuth-core/logger"
  6. "gogs.baozhida.cn/zoie/OAuth-core/pkg"
  7. "gogs.baozhida.cn/zoie/OAuth-core/sdk"
  8. )
  9. type loggerKey struct{}
  10. // GetRequestLogger 获取上下文提供的日志
  11. func GetRequestLogger(c *gin.Context) *logger.Helper {
  12. var log *logger.Helper
  13. l, ok := c.Get(pkg.LoggerKey)
  14. if ok {
  15. ok = false
  16. log, ok = l.(*logger.Helper)
  17. if ok {
  18. return log
  19. }
  20. }
  21. //如果没有在上下文中放入logger
  22. requestId := pkg.GenerateMsgIDFromContext(c)
  23. log = logger.NewHelper(sdk.Runtime.GetLogger()).WithFields(map[string]interface{}{
  24. strings.ToLower(pkg.TrafficKey): requestId,
  25. })
  26. return log
  27. }
  28. // SetRequestLogger 设置logger中间件
  29. func SetRequestLogger(c *gin.Context) {
  30. requestId := pkg.GenerateMsgIDFromContext(c)
  31. log := logger.NewHelper(sdk.Runtime.GetLogger()).WithFields(map[string]interface{}{
  32. strings.ToLower(pkg.TrafficKey): requestId,
  33. })
  34. c.Set(pkg.LoggerKey, log)
  35. }