request_log.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package middleware
  2. import (
  3. "bytes"
  4. "github.com/e421083458/golang_common/lib"
  5. "github.com/gin-gonic/gin"
  6. "github.com/go_gateway_admin/public"
  7. "io/ioutil"
  8. "time"
  9. )
  10. // 请求进入日志
  11. func RequestInLog(c *gin.Context) {
  12. traceContext := lib.NewTrace()
  13. if traceId := c.Request.Header.Get("com-header-rid"); traceId != "" {
  14. traceContext.TraceId = traceId
  15. }
  16. if spanId := c.Request.Header.Get("com-header-spanid"); spanId != "" {
  17. traceContext.SpanId = spanId
  18. }
  19. c.Set("startExecTime", time.Now())
  20. c.Set("trace", traceContext)
  21. bodyBytes, _ := ioutil.ReadAll(c.Request.Body)
  22. c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes)) // Write body back
  23. lib.Log.TagInfo(traceContext, "_com_request_in", map[string]interface{}{
  24. "uri": c.Request.RequestURI,
  25. "method": c.Request.Method,
  26. "args": c.Request.PostForm,
  27. "body": string(bodyBytes),
  28. "from": c.ClientIP(),
  29. })
  30. }
  31. // 请求输出日志
  32. func RequestOutLog(c *gin.Context) {
  33. // after request
  34. endExecTime := time.Now()
  35. response, _ := c.Get("response")
  36. st, _ := c.Get("startExecTime")
  37. startExecTime, _ := st.(time.Time)
  38. public.ComLogNotice(c, "_com_request_out", map[string]interface{}{
  39. "uri": c.Request.RequestURI,
  40. "method": c.Request.Method,
  41. "args": c.Request.PostForm,
  42. "from": c.ClientIP(),
  43. "response": response,
  44. "proc_time": endExecTime.Sub(startExecTime).Seconds(),
  45. })
  46. }
  47. func RequestLog() gin.HandlerFunc {
  48. return func(c *gin.Context) {
  49. RequestInLog(c)
  50. defer RequestOutLog(c)
  51. c.Next()
  52. }
  53. }