[#1437] logger: Use context to log trace id

This commit is contained in:
Dmitrii Stepanov 2024-10-18 13:31:53 +03:00
parent ed13387c0e
commit 0115508863
Signed by: dstepanov-yadro
GPG key ID: 237AF1A763293BC0
3 changed files with 43 additions and 8 deletions

24
pkg/util/logger/log.go Normal file
View file

@ -0,0 +1,24 @@
package logger
import (
"context"
"git.frostfs.info/TrueCloudLab/frostfs-node/pkg/tracing"
"go.uber.org/zap"
)
func (l *Logger) Debug(ctx context.Context, msg string, fields ...zap.Field) {
l.z.Debug(msg, append(fields, zap.String("trace_id", tracing.GetTraceID(ctx)))...)
}
func (l *Logger) Info(ctx context.Context, msg string, fields ...zap.Field) {
l.z.Info(msg, append(fields, zap.String("trace_id", tracing.GetTraceID(ctx)))...)
}
func (l *Logger) Warn(ctx context.Context, msg string, fields ...zap.Field) {
l.z.Info(msg, append(fields, zap.String("trace_id", tracing.GetTraceID(ctx)))...)
}
func (l *Logger) Error(ctx context.Context, msg string, fields ...zap.Field) {
l.z.Info(msg, append(fields, zap.String("trace_id", tracing.GetTraceID(ctx)))...)
}

View file

@ -12,7 +12,7 @@ import (
// Logger represents a component
// for writing messages to log.
type Logger struct {
*zap.Logger
z *zap.Logger
lvl zap.AtomicLevel
}
@ -136,7 +136,7 @@ func newConsoleLogger(prm *Prm) (*Logger, error) {
return nil, err
}
l := &Logger{Logger: lZap, lvl: lvl}
l := &Logger{z: lZap, lvl: lvl}
prm._log = l
return l, nil
@ -169,7 +169,7 @@ func newJournaldLogger(prm *Prm) (*Logger, error) {
lZap := zap.New(coreWithContext, zap.AddStacktrace(zap.NewAtomicLevelAt(zap.FatalLevel)))
l := &Logger{Logger: lZap, lvl: lvl}
l := &Logger{z: lZap, lvl: lvl}
prm._log = l
return l, nil
@ -179,3 +179,13 @@ func (l *Logger) reload(prm Prm) error {
l.lvl.SetLevel(prm.level)
return nil
}
func (l *Logger) WithOptions(options ...zap.Option) {
l.z = l.z.WithOptions(options...)
}
func NewLoggerWrapper(z *zap.Logger) *Logger {
return &Logger{
z: z,
}
}

View file

@ -11,9 +11,10 @@ import (
// NewLogger creates a new logger.
func NewLogger(t testing.TB) *logger.Logger {
var l logger.Logger
l.Logger = zaptest.NewLogger(t,
zaptest.Level(zapcore.DebugLevel),
zaptest.WrapOptions(zap.Development(), zap.AddCaller()))
return &l
return logger.NewLoggerWrapper(
zaptest.NewLogger(t,
zaptest.Level(zapcore.DebugLevel),
zaptest.WrapOptions(zap.Development(), zap.AddCaller()),
),
)
}