tracelogger.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. // WithContext sets ctx to log, for keeping tracing information.
  59. func WithContext(ctx context.Context) Logger {
  60. return &traceLogger{
  61. ctx: ctx,
  62. }
  63. }
  64. func spanIdFromContext(ctx context.Context) string {
  65. t, ok := ctx.Value(tracespec.TracingKey).(tracespec.Trace)
  66. if !ok {
  67. return ""
  68. }
  69. return t.SpanId()
  70. }
  71. func traceIdFromContext(ctx context.Context) string {
  72. t, ok := ctx.Value(tracespec.TracingKey).(tracespec.Trace)
  73. if !ok {
  74. return ""
  75. }
  76. return t.TraceId()
  77. }