Files
fn-serverless/api/common/ctx.go
Dario Domizioli 0a72cb3ef4 Fix missing values in context created with common.BackgroundContext (#950)
* Fix missing values in context when created through common.BackgroundContext

* pin to mysql 5.7.22
2018-04-20 17:29:27 +01:00

67 lines
1.8 KiB
Go

package common
import (
"context"
"time"
"github.com/sirupsen/logrus"
)
type contextKey string
// WithLogger stores the logger.
func WithLogger(ctx context.Context, l logrus.FieldLogger) context.Context {
return context.WithValue(ctx, contextKey("logger"), l)
}
// Logger returns the structured logger.
func Logger(ctx context.Context) logrus.FieldLogger {
l, ok := ctx.Value(contextKey("logger")).(logrus.FieldLogger)
if !ok {
return logrus.StandardLogger()
}
return l
}
// LoggerWithFields returns a child context of the provided parent that
// contains a logger with additional fields from the parent's logger, it
// returns the new child logger, as well.
func LoggerWithFields(ctx context.Context, fields logrus.Fields) (context.Context, logrus.FieldLogger) {
l := Logger(ctx)
l = l.WithFields(fields)
ctx = WithLogger(ctx, l)
return ctx, l
}
// contextWithNoDeadline is an implementation of context.Context which delegates
// Value() to its parent, but it has no deadline and it is never cancelled, just
// like a context.Background().
type contextWithNoDeadline struct {
original context.Context
}
func (ctx *contextWithNoDeadline) Deadline() (deadline time.Time, ok bool) {
return context.Background().Deadline()
}
func (ctx *contextWithNoDeadline) Done() <-chan struct{} {
return context.Background().Done()
}
func (ctx *contextWithNoDeadline) Err() error {
return context.Background().Err()
}
func (ctx *contextWithNoDeadline) Value(key interface{}) interface{} {
return ctx.original.Value(key)
}
// BackgroundContext returns a context that is specifically not a child of the
// provided parent context wrt any cancellation or deadline of the parent,
// so that it contains all values only.
func BackgroundContext(ctx context.Context) context.Context {
return &contextWithNoDeadline{
original: ctx,
}
}