go-zero/core/logx/durationlogger.go

95 lines
2.1 KiB
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package logx
import (
"fmt"
"io"
2022-02-28 23:17:51 +08:00
"sync/atomic"
2020-07-26 17:09:05 +08:00
"time"
"github.com/zeromicro/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{}) {
if shallLog(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{}) {
if shallLog(ErrorLevel) {
l.write(errorLog, levelError, formatWithCaller(fmt.Sprintf(format, v...), durationCallerDepth))
2020-07-26 17:09:05 +08:00
}
}
2021-08-13 18:28:39 +08:00
func (l *durationLogger) Errorv(v interface{}) {
if shallLog(ErrorLevel) {
l.write(errorLog, levelError, v)
}
}
func (l *durationLogger) Info(v ...interface{}) {
if shallLog(InfoLevel) {
2020-07-26 17:09:05 +08:00
l.write(infoLog, levelInfo, fmt.Sprint(v...))
}
}
func (l *durationLogger) Infof(format string, v ...interface{}) {
if shallLog(InfoLevel) {
2020-07-26 17:09:05 +08:00
l.write(infoLog, levelInfo, fmt.Sprintf(format, v...))
}
}
2021-08-13 18:28:39 +08:00
func (l *durationLogger) Infov(v interface{}) {
if shallLog(InfoLevel) {
l.write(infoLog, levelInfo, v)
}
}
func (l *durationLogger) Slow(v ...interface{}) {
if shallLog(ErrorLevel) {
2020-07-26 17:09:05 +08:00
l.write(slowLog, levelSlow, fmt.Sprint(v...))
}
}
func (l *durationLogger) Slowf(format string, v ...interface{}) {
if shallLog(ErrorLevel) {
2020-07-26 17:09:05 +08:00
l.write(slowLog, levelSlow, fmt.Sprintf(format, v...))
}
}
2021-08-13 18:28:39 +08:00
func (l *durationLogger) Slowv(v interface{}) {
if shallLog(ErrorLevel) {
l.write(slowLog, levelSlow, v)
}
}
func (l *durationLogger) WithDuration(duration time.Duration) Logger {
l.Duration = timex.ReprOfDuration(duration)
return l
}
2021-08-13 18:28:39 +08:00
func (l *durationLogger) write(writer io.Writer, level string, val interface{}) {
2022-02-28 23:17:51 +08:00
switch atomic.LoadUint32(&encoding) {
case plainEncodingType:
writePlainAny(writer, level, val, l.Duration)
default:
outputJson(writer, &durationLogger{
Timestamp: getTimestamp(),
Level: level,
Content: val,
Duration: l.Duration,
})
}
2020-07-26 17:09:05 +08:00
}