[#12] Optimize field encoding a bit

No need to clone a map if it is empty.

Signed-off-by: Evgenii Stratonikov <e.stratonikov@yadro.com>
This commit is contained in:
Evgenii Stratonikov 2023-10-18 11:30:19 +03:00
parent f358e67c81
commit 2b6d84de9a
2 changed files with 19 additions and 13 deletions

View file

@ -2,6 +2,7 @@ package zapjournald
import (
"bytes"
"fmt"
"strings"
"go.uber.org/zap/buffer"
@ -9,6 +10,17 @@ import (
var pool = buffer.NewPool()
func encodeJournaldField(buf *buffer.Buffer, key string, value any) {
switch v := value.(type) {
case string:
writeField(buf, key, v)
case []byte:
writeFieldBytes(buf, key, v)
default:
writeField(buf, key, fmt.Sprint(v))
}
}
func writeFieldBytes(buf *buffer.Buffer, name string, value []byte) {
buf.Write([]byte(name))
if bytes.ContainsRune(value, '\n') {

View file

@ -78,20 +78,14 @@ func (core *Core) Write(entry zapcore.Entry, fields []zapcore.Field) error {
writeField(b, "PRIORITY", strconv.Itoa(int(prio)))
structuredFields := maps.Clone(core.contextStructuredFields)
for _, field := range fields {
if _, isJournalField := core.storedFieldNames[field.Key]; isJournalField {
structuredFields[field.Key] = getFieldValue(field)
if len(core.contextStructuredFields) != 0 {
for k, v := range core.contextStructuredFields {
encodeJournaldField(b, k, v)
}
}
for k, v := range structuredFields {
switch v := v.(type) {
case []byte:
writeFieldBytes(b, k, v)
case string:
writeField(b, k, v)
default:
writeField(b, k, fmt.Sprint(v))
for _, field := range fields {
if _, isJournalField := core.storedFieldNames[field.Key]; isJournalField {
encodeJournaldField(b, field.Key, getFieldValue(field))
}
}
}