-
Notifications
You must be signed in to change notification settings - Fork 1
/
logger-context.go
41 lines (36 loc) · 1.03 KB
/
logger-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
38
39
40
41
package logger
import (
"context"
"github.com/gildas/go-errors"
)
type key int
// contextKey is the key for logger child stored in Context
const contextKey key = iota + 12583
// FromContext retrieves the Logger stored in the context
//
// Sources are either LoggerCarrier implemenations or Logger/*Logger objects.
//
// The first source that is a match is returned.
func FromContext(context context.Context, sources ...interface{}) (*Logger, error) {
if context != nil {
if logger, ok := context.Value(contextKey).(*Logger); ok {
return logger, nil
}
}
for _, source := range sources {
if logger, ok := source.(*Logger); ok {
return logger, nil
}
if logger, ok := source.(Logger); ok {
return &logger, nil
}
if carrier, ok := source.(LoggerCarrier); ok {
return carrier.GetLogger(), nil
}
}
return nil, errors.ArgumentMissing.With("Logger")
}
// ToContext stores the Logger in the given context
func (l *Logger) ToContext(parent context.Context) context.Context {
return context.WithValue(parent, contextKey, l)
}