mlog: implement KVerFunc and Prefix

This commit is contained in:
Brian Picciano 2018-07-18 23:01:28 +00:00
parent 0a4be2f8cd
commit 6c17eaa62f
2 changed files with 33 additions and 0 deletions

View File

@ -104,6 +104,14 @@ type KVer interface {
KV() KV KV() KV
} }
// KVerFunc is a function which implements the KVer interface by calling itself.
type KVerFunc func() KV
// KV implements the KVer interface by calling the KVerFunc itself.
func (kvf KVerFunc) KV() KV {
return kvf()
}
// KV is a set of key/value pairs which provides context for a log entry by a // KV is a set of key/value pairs which provides context for a log entry by a
// KVer. KV is itself also a KVer. // KVer. KV is itself also a KVer.
type KV map[string]interface{} type KV map[string]interface{}
@ -170,6 +178,19 @@ func MergeInto(kv KVer, kvs ...KVer) KVer {
return mergeInto(kv, kvs...) return mergeInto(kv, kvs...)
} }
// Prefix prefixes the all keys returned from the given KVer with the given
// prefix string.
func Prefix(kv KVer, prefix string) KVer {
return KVerFunc(func() KV {
kvv := kv.KV()
newKVV := make(KV, len(kvv))
for k, v := range kvv {
newKVV[prefix+k] = v
}
return newKVV
})
}
// Message describes a message to be logged, after having already resolved the // Message describes a message to be logged, after having already resolved the
// KVer // KVer
type Message struct { type Message struct {

View File

@ -9,6 +9,7 @@ import (
. "testing" . "testing"
"time" "time"
"github.com/mediocregopher/mediocre-go-lib/mtest/massert"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
@ -142,3 +143,14 @@ func TestMerge(t *T) {
KV{"a": "a"}, KV{"a": "b"}, KV{"a": "a"}, KV{"a": "b"},
) )
} }
func TestPrefix(t *T) {
kv := KV{"foo": "bar"}
prefixKV := Prefix(kv, "aa")
massert.Fatal(t, massert.All(
massert.Equal(kv.KV(), KV{"foo": "bar"}),
massert.Equal(prefixKV.KV(), KV{"aafoo": "bar"}),
massert.Equal(kv.KV(), KV{"foo": "bar"}),
))
}