logger.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package blademaster
  2. import (
  3. "fmt"
  4. "strconv"
  5. "time"
  6. "go-common/library/ecode"
  7. "go-common/library/log"
  8. "go-common/library/net/metadata"
  9. )
  10. // Logger is logger middleware
  11. func Logger() HandlerFunc {
  12. const noUser = "no_user"
  13. return func(c *Context) {
  14. now := time.Now()
  15. ip := metadata.String(c, metadata.RemoteIP)
  16. req := c.Request
  17. path := req.URL.Path
  18. params := req.Form
  19. var quota float64
  20. if deadline, ok := c.Context.Deadline(); ok {
  21. quota = time.Until(deadline).Seconds()
  22. }
  23. c.Next()
  24. mid, _ := c.Get("mid")
  25. err := c.Error
  26. cerr := ecode.Cause(err)
  27. dt := time.Since(now)
  28. caller := metadata.String(c, metadata.Caller)
  29. if caller == "" {
  30. caller = noUser
  31. }
  32. stats.Incr(caller, path[1:], strconv.FormatInt(int64(cerr.Code()), 10))
  33. stats.Timing(caller, int64(dt/time.Millisecond), path[1:])
  34. lf := log.Infov
  35. errmsg := ""
  36. isSlow := dt >= (time.Millisecond * 500)
  37. if err != nil {
  38. errmsg = err.Error()
  39. lf = log.Errorv
  40. if cerr.Code() > 0 {
  41. lf = log.Warnv
  42. }
  43. } else {
  44. if isSlow {
  45. lf = log.Warnv
  46. }
  47. }
  48. lf(c,
  49. log.KV("method", req.Method),
  50. log.KV("mid", mid),
  51. log.KV("ip", ip),
  52. log.KV("user", caller),
  53. log.KV("path", path),
  54. log.KV("params", params.Encode()),
  55. log.KV("ret", cerr.Code()),
  56. log.KV("msg", cerr.Message()),
  57. log.KV("stack", fmt.Sprintf("%+v", err)),
  58. log.KV("err", errmsg),
  59. log.KV("timeout_quota", quota),
  60. log.KV("ts", dt.Seconds()),
  61. log.KV("source", "http-access-log"),
  62. )
  63. }
  64. }