durationlogger.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package logx
  2. import (
  3. "fmt"
  4. "io"
  5. "time"
  6. "github.com/tal-tech/go-zero/core/timex"
  7. )
  8. const durationCallerDepth = 3
  9. type durationLogger logEntry
  10. // WithDuration returns a Logger which logs the given duration.
  11. func WithDuration(d time.Duration) Logger {
  12. return &durationLogger{
  13. Duration: timex.ReprOfDuration(d),
  14. }
  15. }
  16. func (l *durationLogger) Error(v ...interface{}) {
  17. if shouldLog(ErrorLevel) {
  18. l.write(errorLog, levelError, formatWithCaller(fmt.Sprint(v...), durationCallerDepth))
  19. }
  20. }
  21. func (l *durationLogger) 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 *durationLogger) Info(v ...interface{}) {
  27. if shouldLog(InfoLevel) {
  28. l.write(infoLog, levelInfo, fmt.Sprint(v...))
  29. }
  30. }
  31. func (l *durationLogger) Infof(format string, v ...interface{}) {
  32. if shouldLog(InfoLevel) {
  33. l.write(infoLog, levelInfo, fmt.Sprintf(format, v...))
  34. }
  35. }
  36. func (l *durationLogger) Slow(v ...interface{}) {
  37. if shouldLog(ErrorLevel) {
  38. l.write(slowLog, levelSlow, fmt.Sprint(v...))
  39. }
  40. }
  41. func (l *durationLogger) Slowf(format string, v ...interface{}) {
  42. if shouldLog(ErrorLevel) {
  43. l.write(slowLog, levelSlow, fmt.Sprintf(format, v...))
  44. }
  45. }
  46. func (l *durationLogger) WithDuration(duration time.Duration) Logger {
  47. l.Duration = timex.ReprOfDuration(duration)
  48. return l
  49. }
  50. func (l *durationLogger) write(writer io.Writer, level, content string) {
  51. l.Timestamp = getTimestamp()
  52. l.Level = level
  53. l.Content = content
  54. outputJson(writer, logEntry(*l))
  55. }