go-zero/core/logx/tracelogger.go

94 lines
2.0 KiB
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package logx
import (
"context"
"fmt"
"io"
"time"
2020-07-26 17:09:05 +08:00
"github.com/tal-tech/go-zero/core/timex"
2020-08-08 16:40:10 +08:00
"github.com/tal-tech/go-zero/core/trace/tracespec"
2020-07-26 17:09:05 +08:00
)
type traceLogger struct {
2020-07-26 17:09:05 +08:00
logEntry
2020-09-21 22:41:14 +08:00
Trace string `json:"trace,omitempty"`
Span string `json:"span,omitempty"`
ctx context.Context
2020-07-26 17:09:05 +08:00
}
func (l *traceLogger) 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 *traceLogger) 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 *traceLogger) Info(v ...interface{}) {
2020-07-26 17:09:05 +08:00
if shouldLog(InfoLevel) {
l.write(infoLog, levelInfo, fmt.Sprint(v...))
}
}
func (l *traceLogger) 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 *traceLogger) Slow(v ...interface{}) {
2020-07-26 17:09:05 +08:00
if shouldLog(ErrorLevel) {
l.write(slowLog, levelSlow, fmt.Sprint(v...))
}
}
func (l *traceLogger) 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 *traceLogger) WithDuration(duration time.Duration) Logger {
l.Duration = timex.ReprOfDuration(duration)
return l
}
func (l *traceLogger) write(writer io.Writer, level, content string) {
2020-07-26 17:09:05 +08:00
l.Timestamp = getTimestamp()
l.Level = level
l.Content = content
l.Trace = traceIdFromContext(l.ctx)
l.Span = spanIdFromContext(l.ctx)
outputJson(writer, l)
}
2021-02-20 22:45:58 +08:00
// WithContext sets ctx to log, for keeping tracing infomation.
2020-07-26 17:09:05 +08:00
func WithContext(ctx context.Context) Logger {
return &traceLogger{
2020-07-26 17:09:05 +08:00
ctx: ctx,
}
}
func spanIdFromContext(ctx context.Context) string {
t, ok := ctx.Value(tracespec.TracingKey).(tracespec.Trace)
if !ok {
return ""
}
return t.SpanId()
}
func traceIdFromContext(ctx context.Context) string {
t, ok := ctx.Value(tracespec.TracingKey).(tracespec.Trace)
if !ok {
return ""
}
return t.TraceId()
}