mlog: refactor From to include Component's Context implicitly
This commit is contained in:
parent
7f9b0d5591
commit
7eac20f58b
24
mlog/cmp.go
24
mlog/cmp.go
@ -2,6 +2,7 @@ package mlog
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/mediocregopher/mediocre-go-lib/mcmp"
|
"github.com/mediocregopher/mediocre-go-lib/mcmp"
|
||||||
|
"github.com/mediocregopher/mediocre-go-lib/mctx"
|
||||||
)
|
)
|
||||||
|
|
||||||
type cmpKey int
|
type cmpKey int
|
||||||
@ -19,10 +20,29 @@ var DefaultLogger = NewLogger()
|
|||||||
// From returns the Logger which was set on the Component, or one of its
|
// From returns the Logger which was set on the Component, or one of its
|
||||||
// ancestors, using SetLogger. If no Logger was ever set then DefaultLogger is
|
// ancestors, using SetLogger. If no Logger was ever set then DefaultLogger is
|
||||||
// returned.
|
// returned.
|
||||||
|
//
|
||||||
|
// The returned Logger will be modified such that it will implicitly merge the
|
||||||
|
// Contexts of any Message into the given Component's Context.
|
||||||
func From(cmp *mcmp.Component) *Logger {
|
func From(cmp *mcmp.Component) *Logger {
|
||||||
l, _ := cmp.Value(cmpKey(0)).(*Logger)
|
var l *Logger
|
||||||
if l == nil {
|
if l, _ = cmp.Value(cmpKey(1)).(*Logger); l != nil {
|
||||||
|
return l
|
||||||
|
} else if lInt, ok := cmp.InheritedValue(cmpKey(0)); ok {
|
||||||
|
l = lInt.(*Logger)
|
||||||
|
} else {
|
||||||
l = DefaultLogger
|
l = DefaultLogger
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// if we're here it means a modified Logger wasn't set on this particular
|
||||||
|
// Component, and therefore the current one must be modified.
|
||||||
|
l = l.Clone()
|
||||||
|
oldHandler := l.Handler()
|
||||||
|
l.SetHandler(func(msg Message) error {
|
||||||
|
ctx := mctx.MergeAnnotationsInto(cmp.Context(), msg.Contexts...)
|
||||||
|
msg.Contexts = append(msg.Contexts[:0], ctx)
|
||||||
|
return oldHandler(msg)
|
||||||
|
})
|
||||||
|
cmp.SetValue(cmpKey(1), l)
|
||||||
|
|
||||||
return l
|
return l
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user