-
Notifications
You must be signed in to change notification settings - Fork 7
/
context.go
37 lines (30 loc) · 1.05 KB
/
context.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package util
import (
"context"
log "github.com/Sirupsen/logrus"
)
// contextKeys is a type alias for string to namespace Context keys per-package.
type contextKeys string
// ctxValueRequestID is the key to extract the request ID for an HTTP request
const ctxValueRequestID = contextKeys("requestid")
// GetRequestID returns the request ID associated with this context, or the empty string
// if one is not associated with this context.
func GetRequestID(ctx context.Context) string {
id := ctx.Value(ctxValueRequestID)
if id == nil {
return ""
}
return id.(string)
}
// ctxValueLogger is the key to extract the logrus Logger.
const ctxValueLogger = contextKeys("logger")
// GetLogger retrieves the logrus logger from the supplied context. Always returns a logger,
// even if there wasn't one originally supplied.
func GetLogger(ctx context.Context) *log.Entry {
l := ctx.Value(ctxValueLogger)
if l == nil {
// Always return a logger so callers don't need to constantly nil check.
return log.WithField("context", "missing")
}
return l.(*log.Entry)
}