Skip to content

Commit

Permalink
optimize "WithValues" func
Browse files Browse the repository at this point in the history
  • Loading branch information
SergeyMosin committed Jan 14, 2022
1 parent 829d96b commit 46bfce7
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 13 deletions.
27 changes: 15 additions & 12 deletions sdlogr.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ func NewWithOptions(opts Options) logr.Logger {
depth: opts.Depth + 1,
logCallerInfo: opts.LogCallerInfo,
out: opts.Out,
valuesMap: make(map[string]interface{}, 1),
valuesMap: make(map[string]string, 1),
}
return logr.New(&l)
}
Expand All @@ -80,7 +80,7 @@ type sdLogr struct {
level int
depth int
prefix string
valuesMap map[string]interface{}
valuesMap map[string]string
valuesStr string
out io.Writer
logCallerInfo bool
Expand Down Expand Up @@ -197,21 +197,24 @@ func (l sdLogr) WithValues(kvList ...interface{}) logr.LogSink {
n++
}

l.valuesStr = ""
var lastKey *string
for i := 0; i < n; i++ {
k := kvList[i]
if k == "" {
k = emptyStringPlaceholder
kvi := kvList[i]
if kvi == "" {
kvi = emptyStringPlaceholder
}
kv := fmt.Sprintf("%v", deref(kvi))
if (i & 1) == 0 {
// kv is key
lastKey = &kv
} else {
// kv is value
l.valuesMap[*lastKey] = kv
}
i++
l.valuesMap[fmt.Sprintf("%v", deref(k))] = kvList[i]
}

// rebuild the string
l.valuesStr = ""
for k, v := range l.valuesMap {
if v == "" {
v = emptyStringPlaceholder
}
l.valuesStr += k + ": " + fmt.Sprintf("%v", deref(v)) + ", "
}
return &l
Expand Down
2 changes: 1 addition & 1 deletion sdlogr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ func TestWithValues(t *testing.T) {
log = log.WithValues("vv", "vvk")
log.Info("msg1")
log = log.WithValues("vv", "vvk")
log.Info("msg2")
log.Info("msg2", "vv", "v")
log = log.WithValues("vv1", "vvk")
log.Info("msg3")
}
Expand Down

0 comments on commit 46bfce7

Please sign in to comment.