durationlogger.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package logx
  2. import (
  3. "fmt"
  4. "io"
  5. "sync/atomic"
  6. "time"
  7. "github.com/zeromicro/go-zero/core/timex"
  8. )
  9. const durationCallerDepth = 3
  10. type durationLogger logEntry
  11. // WithDuration returns a Logger which logs the given duration.
  12. func WithDuration(d time.Duration) Logger {
  13. return &durationLogger{
  14. Duration: timex.ReprOfDuration(d),
  15. }
  16. }
  17. func (l *durationLogger) Error(v ...interface{}) {
  18. if shallLog(ErrorLevel) {
  19. l.write(errorLog, levelError, formatWithCaller(fmt.Sprint(v...), durationCallerDepth))
  20. }
  21. }
  22. func (l *durationLogger) Errorf(format string, v ...interface{}) {
  23. if shallLog(ErrorLevel) {
  24. l.write(errorLog, levelError, formatWithCaller(fmt.Sprintf(format, v...), durationCallerDepth))
  25. }
  26. }
  27. func (l *durationLogger) Errorv(v interface{}) {
  28. if shallLog(ErrorLevel) {
  29. l.write(errorLog, levelError, v)
  30. }
  31. }
  32. func (l *durationLogger) Info(v ...interface{}) {
  33. if shallLog(InfoLevel) {
  34. l.write(infoLog, levelInfo, fmt.Sprint(v...))
  35. }
  36. }
  37. func (l *durationLogger) Infof(format string, v ...interface{}) {
  38. if shallLog(InfoLevel) {
  39. l.write(infoLog, levelInfo, fmt.Sprintf(format, v...))
  40. }
  41. }
  42. func (l *durationLogger) Infov(v interface{}) {
  43. if shallLog(InfoLevel) {
  44. l.write(infoLog, levelInfo, v)
  45. }
  46. }
  47. func (l *durationLogger) Slow(v ...interface{}) {
  48. if shallLog(ErrorLevel) {
  49. l.write(slowLog, levelSlow, fmt.Sprint(v...))
  50. }
  51. }
  52. func (l *durationLogger) Slowf(format string, v ...interface{}) {
  53. if shallLog(ErrorLevel) {
  54. l.write(slowLog, levelSlow, fmt.Sprintf(format, v...))
  55. }
  56. }
  57. func (l *durationLogger) Slowv(v interface{}) {
  58. if shallLog(ErrorLevel) {
  59. l.write(slowLog, levelSlow, v)
  60. }
  61. }
  62. func (l *durationLogger) WithDuration(duration time.Duration) Logger {
  63. l.Duration = timex.ReprOfDuration(duration)
  64. return l
  65. }
  66. func (l *durationLogger) write(writer io.Writer, level string, val interface{}) {
  67. switch atomic.LoadUint32(&encoding) {
  68. case plainEncodingType:
  69. writePlainAny(writer, level, val, l.Duration)
  70. default:
  71. outputJson(writer, &durationLogger{
  72. Timestamp: getTimestamp(),
  73. Level: level,
  74. Content: val,
  75. Duration: l.Duration,
  76. })
  77. }
  78. }