tracelogger.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package logx
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "time"
  7. "github.com/tal-tech/go-zero/core/timex"
  8. "github.com/tal-tech/go-zero/core/trace/tracespec"
  9. )
  10. type traceLogger struct {
  11. logEntry
  12. Trace string `json:"trace,omitempty"`
  13. Span string `json:"span,omitempty"`
  14. ctx context.Context
  15. }
  16. func (l *traceLogger) Error(v ...interface{}) {
  17. if shouldLog(ErrorLevel) {
  18. l.write(errorLog, levelError, formatWithCaller(fmt.Sprint(v...), durationCallerDepth))
  19. }
  20. }
  21. func (l *traceLogger) Errorf(format string, v ...interface{}) {
  22. if shouldLog(ErrorLevel) {
  23. l.write(errorLog, levelError, formatWithCaller(fmt.Sprintf(format, v...), durationCallerDepth))
  24. }
  25. }
  26. func (l *traceLogger) Info(v ...interface{}) {
  27. if shouldLog(InfoLevel) {
  28. l.write(infoLog, levelInfo, fmt.Sprint(v...))
  29. }
  30. }
  31. func (l *traceLogger) Infof(format string, v ...interface{}) {
  32. if shouldLog(InfoLevel) {
  33. l.write(infoLog, levelInfo, fmt.Sprintf(format, v...))
  34. }
  35. }
  36. func (l *traceLogger) Slow(v ...interface{}) {
  37. if shouldLog(ErrorLevel) {
  38. l.write(slowLog, levelSlow, fmt.Sprint(v...))
  39. }
  40. }
  41. func (l *traceLogger) Slowf(format string, v ...interface{}) {
  42. if shouldLog(ErrorLevel) {
  43. l.write(slowLog, levelSlow, fmt.Sprintf(format, v...))
  44. }
  45. }
  46. func (l *traceLogger) WithDuration(duration time.Duration) Logger {
  47. l.Duration = timex.ReprOfDuration(duration)
  48. return l
  49. }
  50. func (l *traceLogger) write(writer io.Writer, level, content string) {
  51. l.Timestamp = getTimestamp()
  52. l.Level = level
  53. l.Content = content
  54. l.Trace = traceIdFromContext(l.ctx)
  55. l.Span = spanIdFromContext(l.ctx)
  56. outputJson(writer, l)
  57. }
  58. func WithContext(ctx context.Context) Logger {
  59. return &traceLogger{
  60. ctx: ctx,
  61. }
  62. }
  63. func spanIdFromContext(ctx context.Context) string {
  64. t, ok := ctx.Value(tracespec.TracingKey).(tracespec.Trace)
  65. if !ok {
  66. return ""
  67. }
  68. return t.SpanId()
  69. }
  70. func traceIdFromContext(ctx context.Context) string {
  71. t, ok := ctx.Value(tracespec.TracingKey).(tracespec.Trace)
  72. if !ok {
  73. return ""
  74. }
  75. return t.TraceId()
  76. }