log.go 1.6 KB

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