tracelog.go 1.8 KB

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