From 2b6d84de9a3db3894b41cda183e411b8e574a2e6 Mon Sep 17 00:00:00 2001 From: Evgenii Stratonikov Date: Wed, 18 Oct 2023 11:30:19 +0300 Subject: [PATCH] [#12] Optimize field encoding a bit No need to clone a map if it is empty. Signed-off-by: Evgenii Stratonikov --- encoder.go | 12 ++++++++++++ zapjournald.go | 20 +++++++------------- 2 files changed, 19 insertions(+), 13 deletions(-) diff --git a/encoder.go b/encoder.go index 9ba9369..1a00d52 100644 --- a/encoder.go +++ b/encoder.go @@ -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') { diff --git a/zapjournald.go b/zapjournald.go index 27ea5d0..1c562bc 100644 --- a/zapjournald.go +++ b/zapjournald.go @@ -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)) + } } }