Logging: Introduce API for contextual logging (#55198)

Introduces a FromContext method on the log.Logger interface that 
allows contextual key/value pairs to be attached, e.g. per request, 
so that any logger using this API will automatically get the per request 
context attached. The proposal makes the traceID available for 
contextual logger , if available, and would allow logs originating from 
a certain HTTP request to be correlated with traceID.
In addition, when tracing not enabled, skip adding
traceID=00000000000000000000000000000000
to logs.
This commit is contained in:
Marcus Efraimsson
2022-09-20 18:32:06 +02:00
committed by GitHub
parent c6ed7d6741
commit 862a6a2fa6
17 changed files with 202 additions and 55 deletions

View File

@@ -48,8 +48,10 @@ func inTransactionWithRetryCtx(ctx context.Context, engine *xorm.Engine, bus bus
err = callback(sess)
ctxLogger := tsclogger.FromContext(ctx)
if !isNew {
tsclogger.Debug("skip committing the transaction because it belongs to a session created in the outer scope")
ctxLogger.Debug("skip committing the transaction because it belongs to a session created in the outer scope")
// Do not commit the transaction if the session was reused.
return err
}
@@ -62,7 +64,7 @@ func inTransactionWithRetryCtx(ctx context.Context, engine *xorm.Engine, bus bus
}
time.Sleep(time.Millisecond * time.Duration(10))
sqlog.Info("Database locked, sleeping then retrying", "error", err, "retry", retry)
ctxLogger.Info("Database locked, sleeping then retrying", "error", err, "retry", retry)
return inTransactionWithRetryCtx(ctx, engine, bus, callback, retry+1)
}
@@ -79,7 +81,7 @@ func inTransactionWithRetryCtx(ctx context.Context, engine *xorm.Engine, bus bus
if len(sess.events) > 0 {
for _, e := range sess.events {
if err = bus.Publish(ctx, e); err != nil {
tsclogger.Error("Failed to publish event after commit.", "error", err)
ctxLogger.Error("Failed to publish event after commit.", "error", err)
}
}
}