You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/core/logx/tracelogger.go

112 lines
2.3 KiB
Go

4 years ago
package logx
import (
"context"
"fmt"
"io"
"time"
4 years ago
"github.com/tal-tech/go-zero/core/timex"
"github.com/tal-tech/go-zero/core/trace/tracespec"
4 years ago
)
type traceLogger struct {
4 years ago
logEntry
Trace string `json:"trace,omitempty"`
Span string `json:"span,omitempty"`
ctx context.Context
4 years ago
}
func (l *traceLogger) Error(v ...interface{}) {
if shallLog(ErrorLevel) {
l.write(errorLog, levelError, formatWithCaller(fmt.Sprint(v...), durationCallerDepth))
4 years ago
}
}
func (l *traceLogger) Errorf(format string, v ...interface{}) {
if shallLog(ErrorLevel) {
l.write(errorLog, levelError, formatWithCaller(fmt.Sprintf(format, v...), durationCallerDepth))
4 years ago
}
}
func (l *traceLogger) Errorv(v interface{}) {
if shallLog(ErrorLevel) {
l.write(errorLog, levelError, v)
}
}
func (l *traceLogger) Info(v ...interface{}) {
if shallLog(InfoLevel) {
4 years ago
l.write(infoLog, levelInfo, fmt.Sprint(v...))
}
}
func (l *traceLogger) Infof(format string, v ...interface{}) {
if shallLog(InfoLevel) {
4 years ago
l.write(infoLog, levelInfo, fmt.Sprintf(format, v...))
}
}
func (l *traceLogger) Infov(v interface{}) {
if shallLog(InfoLevel) {
l.write(infoLog, levelInfo, v)
}
}
func (l *traceLogger) Slow(v ...interface{}) {
if shallLog(ErrorLevel) {
4 years ago
l.write(slowLog, levelSlow, fmt.Sprint(v...))
}
}
func (l *traceLogger) Slowf(format string, v ...interface{}) {
if shallLog(ErrorLevel) {
4 years ago
l.write(slowLog, levelSlow, fmt.Sprintf(format, v...))
}
}
func (l *traceLogger) Slowv(v interface{}) {
if shallLog(ErrorLevel) {
l.write(slowLog, levelSlow, v)
}
}
func (l *traceLogger) WithDuration(duration time.Duration) Logger {
l.Duration = timex.ReprOfDuration(duration)
return l
}
func (l *traceLogger) write(writer io.Writer, level string, val interface{}) {
4 years ago
l.Timestamp = getTimestamp()
l.Level = level
l.Content = val
4 years ago
l.Trace = traceIdFromContext(l.ctx)
l.Span = spanIdFromContext(l.ctx)
outputJson(writer, l)
}
// WithContext sets ctx to log, for keeping tracing information.
4 years ago
func WithContext(ctx context.Context) Logger {
return &traceLogger{
4 years ago
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()
}