log.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. var LogContext = contextKey("request_logs")
  11. type LogCollector struct {
  12. Messages []string
  13. lock sync.Mutex
  14. }
  15. func (lc *LogCollector) Append(msg string) {
  16. lc.lock.Lock()
  17. lc.Messages = append(lc.Messages, msg)
  18. lc.lock.Unlock()
  19. }
  20. func (lc *LogCollector) Flush() string {
  21. var buffer bytes.Buffer
  22. start := true
  23. for _, message := range lc.takeAll() {
  24. if start {
  25. start = false
  26. } else {
  27. buffer.WriteByte('\n')
  28. }
  29. buffer.WriteString(message)
  30. }
  31. return buffer.String()
  32. }
  33. func (lc *LogCollector) takeAll() []string {
  34. lc.lock.Lock()
  35. messages := lc.Messages
  36. lc.Messages = nil
  37. lc.lock.Unlock()
  38. return messages
  39. }
  40. func Error(r *http.Request, v ...interface{}) {
  41. logx.ErrorCaller(1, format(r, v...))
  42. }
  43. func Errorf(r *http.Request, format string, v ...interface{}) {
  44. logx.ErrorCaller(1, formatf(r, format, v...))
  45. }
  46. func Info(r *http.Request, v ...interface{}) {
  47. appendLog(r, format(r, v...))
  48. }
  49. func Infof(r *http.Request, format string, v ...interface{}) {
  50. appendLog(r, formatf(r, format, v...))
  51. }
  52. func appendLog(r *http.Request, message string) {
  53. logs := r.Context().Value(LogContext)
  54. if logs != nil {
  55. logs.(*LogCollector).Append(message)
  56. }
  57. }
  58. func format(r *http.Request, v ...interface{}) string {
  59. return formatWithReq(r, fmt.Sprint(v...))
  60. }
  61. func formatf(r *http.Request, format string, v ...interface{}) string {
  62. return formatWithReq(r, fmt.Sprintf(format, v...))
  63. }
  64. func formatWithReq(r *http.Request, v string) string {
  65. return fmt.Sprintf("(%s - %s) %s", r.RequestURI, httpx.GetRemoteAddr(r), v)
  66. }
  67. type contextKey string
  68. func (c contextKey) String() string {
  69. return "rest/internal context key " + string(c)
  70. }