durationlogger.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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 shallLog(ErrorLevel) {
  18. l.write(errorLog, levelError, formatWithCaller(fmt.Sprint(v...), durationCallerDepth))
  19. }
  20. }
  21. func (l *durationLogger) Errorf(format string, v ...interface{}) {
  22. if shallLog(ErrorLevel) {
  23. l.write(errorLog, levelError, formatWithCaller(fmt.Sprintf(format, v...), durationCallerDepth))
  24. }
  25. }
  26. func (l *durationLogger) Errorv(v interface{}) {
  27. if shallLog(ErrorLevel) {
  28. l.write(errorLog, levelError, v)
  29. }
  30. }
  31. func (l *durationLogger) Info(v ...interface{}) {
  32. if shallLog(InfoLevel) {
  33. l.write(infoLog, levelInfo, fmt.Sprint(v...))
  34. }
  35. }
  36. func (l *durationLogger) Infof(format string, v ...interface{}) {
  37. if shallLog(InfoLevel) {
  38. l.write(infoLog, levelInfo, fmt.Sprintf(format, v...))
  39. }
  40. }
  41. func (l *durationLogger) Infov(v interface{}) {
  42. if shallLog(InfoLevel) {
  43. l.write(infoLog, levelInfo, v)
  44. }
  45. }
  46. func (l *durationLogger) Slow(v ...interface{}) {
  47. if shallLog(ErrorLevel) {
  48. l.write(slowLog, levelSlow, fmt.Sprint(v...))
  49. }
  50. }
  51. func (l *durationLogger) Slowf(format string, v ...interface{}) {
  52. if shallLog(ErrorLevel) {
  53. l.write(slowLog, levelSlow, fmt.Sprintf(format, v...))
  54. }
  55. }
  56. func (l *durationLogger) Slowv(v interface{}) {
  57. if shallLog(ErrorLevel) {
  58. l.write(slowLog, levelSlow, v)
  59. }
  60. }
  61. func (l *durationLogger) WithDuration(duration time.Duration) Logger {
  62. l.Duration = timex.ReprOfDuration(duration)
  63. return l
  64. }
  65. func (l *durationLogger) write(writer io.Writer, level string, val interface{}) {
  66. l.Timestamp = getTimestamp()
  67. l.Level = level
  68. l.Content = val
  69. outputJson(writer, l)
  70. }