[#148] Add trace_id to logs
Signed-off-by: Roman Loginov <r.loginov@yadro.com>
This commit is contained in:
parent
495f745535
commit
fc86ab3511
7 changed files with 104 additions and 48 deletions
|
@ -4,6 +4,7 @@ import (
|
|||
"context"
|
||||
|
||||
"github.com/valyala/fasthttp"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// SetContextToRequest adds new context to fasthttp request.
|
||||
|
@ -15,3 +16,34 @@ func SetContextToRequest(ctx context.Context, c *fasthttp.RequestCtx) {
|
|||
func GetContextFromRequest(c *fasthttp.RequestCtx) context.Context {
|
||||
return c.UserValue("context").(context.Context)
|
||||
}
|
||||
|
||||
type ctxReqLoggerKeyType struct{}
|
||||
|
||||
// SetReqLog sets child zap.Logger in the context.
|
||||
func SetReqLog(ctx context.Context, log *zap.Logger) context.Context {
|
||||
if ctx == nil {
|
||||
return nil
|
||||
}
|
||||
return context.WithValue(ctx, ctxReqLoggerKeyType{}, log)
|
||||
}
|
||||
|
||||
// GetReqLog returns log if set.
|
||||
// If zap.Logger isn't set returns nil.
|
||||
func GetReqLog(ctx context.Context) *zap.Logger {
|
||||
if ctx == nil {
|
||||
return nil
|
||||
} else if r, ok := ctx.Value(ctxReqLoggerKeyType{}).(*zap.Logger); ok {
|
||||
return r
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetReqLogOrDefault returns log from context, if it exists.
|
||||
// If the log is missing from the context, the default logger is returned.
|
||||
func GetReqLogOrDefault(ctx context.Context, defaultLog *zap.Logger) *zap.Logger {
|
||||
log := GetReqLog(ctx)
|
||||
if log == nil {
|
||||
log = defaultLog
|
||||
}
|
||||
return log
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue