durationlogger.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. func WithDuration(d time.Duration) Logger {
  11. return &durationLogger{
  12. Duration: timex.ReprOfDuration(d),
  13. }
  14. }
  15. func (l *durationLogger) Error(v ...interface{}) {
  16. if shouldLog(ErrorLevel) {
  17. l.write(errorLog, levelError, formatWithCaller(fmt.Sprint(v...), durationCallerDepth))
  18. }
  19. }
  20. func (l *durationLogger) Errorf(format string, v ...interface{}) {
  21. if shouldLog(ErrorLevel) {
  22. l.write(errorLog, levelError, formatWithCaller(fmt.Sprintf(format, v...), durationCallerDepth))
  23. }
  24. }
  25. func (l *durationLogger) Info(v ...interface{}) {
  26. if shouldLog(InfoLevel) {
  27. l.write(infoLog, levelInfo, fmt.Sprint(v...))
  28. }
  29. }
  30. func (l *durationLogger) Infof(format string, v ...interface{}) {
  31. if shouldLog(InfoLevel) {
  32. l.write(infoLog, levelInfo, fmt.Sprintf(format, v...))
  33. }
  34. }
  35. func (l *durationLogger) Slow(v ...interface{}) {
  36. if shouldLog(ErrorLevel) {
  37. l.write(slowLog, levelSlow, fmt.Sprint(v...))
  38. }
  39. }
  40. func (l *durationLogger) Slowf(format string, v ...interface{}) {
  41. if shouldLog(ErrorLevel) {
  42. l.write(slowLog, levelSlow, fmt.Sprintf(format, v...))
  43. }
  44. }
  45. func (l *durationLogger) WithDuration(duration time.Duration) Logger {
  46. l.Duration = timex.ReprOfDuration(duration)
  47. return l
  48. }
  49. func (l *durationLogger) write(writer io.Writer, level, content string) {
  50. l.Timestamp = getTimestamp()
  51. l.Level = level
  52. l.Content = content
  53. outputJson(writer, logEntry(*l))
  54. }