go-zero/core/logx/durationlogger.go

69 lines
1.5 KiB
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package logx
import (
"fmt"
"io"
"time"
2020-08-08 16:40:10 +08:00
"github.com/tal-tech/go-zero/core/timex"
2020-07-26 17:09:05 +08:00
)
const durationCallerDepth = 3
2020-07-26 17:09:05 +08:00
type durationLogger logEntry
2020-07-26 17:09:05 +08:00
2021-02-20 22:45:58 +08:00
// WithDuration returns a Logger which logs the given duration.
2020-07-26 17:09:05 +08:00
func WithDuration(d time.Duration) Logger {
return &durationLogger{
2020-07-26 17:09:05 +08:00
Duration: timex.ReprOfDuration(d),
}
}
func (l *durationLogger) Error(v ...interface{}) {
2020-07-26 17:09:05 +08:00
if shouldLog(ErrorLevel) {
l.write(errorLog, levelError, formatWithCaller(fmt.Sprint(v...), durationCallerDepth))
2020-07-26 17:09:05 +08:00
}
}
func (l *durationLogger) Errorf(format string, v ...interface{}) {
2020-07-26 17:09:05 +08:00
if shouldLog(ErrorLevel) {
l.write(errorLog, levelError, formatWithCaller(fmt.Sprintf(format, v...), durationCallerDepth))
2020-07-26 17:09:05 +08:00
}
}
func (l *durationLogger) Info(v ...interface{}) {
2020-07-26 17:09:05 +08:00
if shouldLog(InfoLevel) {
l.write(infoLog, levelInfo, fmt.Sprint(v...))
}
}
func (l *durationLogger) Infof(format string, v ...interface{}) {
2020-07-26 17:09:05 +08:00
if shouldLog(InfoLevel) {
l.write(infoLog, levelInfo, fmt.Sprintf(format, v...))
}
}
func (l *durationLogger) Slow(v ...interface{}) {
2020-07-26 17:09:05 +08:00
if shouldLog(ErrorLevel) {
l.write(slowLog, levelSlow, fmt.Sprint(v...))
}
}
func (l *durationLogger) Slowf(format string, v ...interface{}) {
2020-07-26 17:09:05 +08:00
if shouldLog(ErrorLevel) {
l.write(slowLog, levelSlow, fmt.Sprintf(format, v...))
}
}
func (l *durationLogger) WithDuration(duration time.Duration) Logger {
l.Duration = timex.ReprOfDuration(duration)
return l
}
func (l *durationLogger) write(writer io.Writer, level, content string) {
2020-07-26 17:09:05 +08:00
l.Timestamp = getTimestamp()
l.Level = level
l.Content = content
outputJson(writer, logEntry(*l))
2020-07-26 17:09:05 +08:00
}