log.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package internal
  2. import (
  3. "bytes"
  4. "fmt"
  5. "net/http"
  6. "sync"
  7. "github.com/tal-tech/go-zero/core/logx"
  8. "github.com/tal-tech/go-zero/rest/httpx"
  9. )
  10. // LogContext is a context key.
  11. var LogContext = contextKey("request_logs")
  12. // A LogCollector is used to collect logs.
  13. type LogCollector struct {
  14. Messages []string
  15. lock sync.Mutex
  16. }
  17. // Append appends msg into log context.
  18. func (lc *LogCollector) Append(msg string) {
  19. lc.lock.Lock()
  20. lc.Messages = append(lc.Messages, msg)
  21. lc.lock.Unlock()
  22. }
  23. // Flush flushes collected logs.
  24. func (lc *LogCollector) Flush() string {
  25. var buffer bytes.Buffer
  26. start := true
  27. for _, message := range lc.takeAll() {
  28. if start {
  29. start = false
  30. } else {
  31. buffer.WriteByte('\n')
  32. }
  33. buffer.WriteString(message)
  34. }
  35. return buffer.String()
  36. }
  37. func (lc *LogCollector) takeAll() []string {
  38. lc.lock.Lock()
  39. messages := lc.Messages
  40. lc.Messages = nil
  41. lc.lock.Unlock()
  42. return messages
  43. }
  44. // Error logs the given v along with r in error log.
  45. func Error(r *http.Request, v ...interface{}) {
  46. logx.ErrorCaller(1, format(r, v...))
  47. }
  48. // Errorf logs the given v with format along with r in error log.
  49. func Errorf(r *http.Request, format string, v ...interface{}) {
  50. logx.ErrorCaller(1, formatf(r, format, v...))
  51. }
  52. // Info logs the given v along with r in access log.
  53. func Info(r *http.Request, v ...interface{}) {
  54. appendLog(r, format(r, v...))
  55. }
  56. // Infof logs the given v with format along with r in access log.
  57. func Infof(r *http.Request, format string, v ...interface{}) {
  58. appendLog(r, formatf(r, format, v...))
  59. }
  60. func appendLog(r *http.Request, message string) {
  61. logs := r.Context().Value(LogContext)
  62. if logs != nil {
  63. logs.(*LogCollector).Append(message)
  64. }
  65. }
  66. func format(r *http.Request, v ...interface{}) string {
  67. return formatWithReq(r, fmt.Sprint(v...))
  68. }
  69. func formatf(r *http.Request, format string, v ...interface{}) string {
  70. return formatWithReq(r, fmt.Sprintf(format, v...))
  71. }
  72. func formatWithReq(r *http.Request, v string) string {
  73. return fmt.Sprintf("(%s - %s) %s", r.RequestURI, httpx.GetRemoteAddr(r), v)
  74. }
  75. type contextKey string
  76. func (c contextKey) String() string {
  77. return "rest/internal context key " + string(c)
  78. }