Skip to content

Commit 34fa3f4

Browse files
committed
logging.journaldCore: Fix key encoding of all fields
The encodeJournaldFieldKey function sanitizes the keys for the journald fields. However, calling the AddTo method on some zap fields results in multiple output fields. The keys of these additional fields are not sanitized and may not comply with journald's requirements. This change applies name sanitation after all fields were added, thereby including also these surplus fields. As a result, errors are now also available as "ERROR_VERBOSE", including a potential stack trace.
1 parent a520688 commit 34fa3f4

File tree

1 file changed

+10
-5
lines changed

1 file changed

+10
-5
lines changed

logging/journald_core.go

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -67,24 +67,29 @@ func (c *journaldCore) Write(ent zapcore.Entry, fields []zapcore.Field) error {
6767
}
6868

6969
enc := zapcore.NewMapObjectEncoder()
70-
// Ensure that all field keys are valid journald field keys. If in doubt, use encodeJournaldFieldKey.
7170
c.addFields(enc, fields)
7271
c.addFields(enc, c.context)
7372
enc.Fields["SYSLOG_IDENTIFIER"] = c.identifier
7473

74+
// Re-encode keys before passing them to journald. Unfortunately, this cannot be done within addFields or at another
75+
// earlier position since zapcore's Field.AddTo may create multiple entries, some with non-compliant names.
76+
encFields := make(map[string]interface{})
77+
for k, v := range enc.Fields {
78+
encFields[encodeJournaldFieldKey(k)] = v
79+
}
80+
7581
message := ent.Message + visibleFieldsMsg(journaldVisibleFields, append(fields, c.context...))
7682
if ent.LoggerName != c.identifier {
7783
message = ent.LoggerName + ": " + message
7884
}
7985

80-
return journald.Send(message, pri, enc.Fields)
86+
return journald.Send(message, pri, encFields)
8187
}
8288

83-
// addFields adds all given fields to enc with an altered key, prefixed with the journaldCore.identifier and sanitized
84-
// via encodeJournaldFieldKey.
89+
// addFields adds all given fields to enc with an altered key, prefixed with the journaldCore.identifier.
8590
func (c *journaldCore) addFields(enc zapcore.ObjectEncoder, fields []zapcore.Field) {
8691
for _, field := range fields {
87-
field.Key = encodeJournaldFieldKey(c.identifier + "_" + field.Key)
92+
field.Key = c.identifier + "_" + field.Key
8893
field.AddTo(enc)
8994
}
9095
}

0 commit comments

Comments
 (0)