Skip to content

Commit b8f068a

Browse files
committed
Add a WithKeyFormatter option
Currently the key used when converting a message field into a slog.Attr defaults to the fields name. The function provided via this option can alter the key depending on the field and its value.
1 parent da831e9 commit b8f068a

File tree

1 file changed

+22
-1
lines changed

1 file changed

+22
-1
lines changed

options.go

+22-1
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,10 @@ var (
2020
unknownValue = slog.StringValue("UNKNOWN")
2121
)
2222

23+
// KeyFormatter functions provide a way to alter a [slog.Attr] key depending
24+
// on the to be logged field of a [protoreflect.Message].
25+
type KeyFormatter func(key string, fd protoreflect.FieldDescriptor, value protoreflect.Value) string
26+
2327
// Option functions customize generation of a [slog.Value] from a
2428
// [proto.Message] beyond the default behavior.
2529
type Option func(o *options)
@@ -61,6 +65,12 @@ func WithAnyResolver(resolver protoregistry.MessageTypeResolver) Option {
6165
return func(o *options) { o.AnyResolver = resolver }
6266
}
6367

68+
// WithKeyFormatter is used to alter a [slog.Attr] key depending
69+
// on the to be logged field of a [protoreflect.Message].
70+
func WithKeyFormatter(formatter KeyFormatter) Option {
71+
return func(o *options) { o.KeyFormatter = formatter }
72+
}
73+
6474
type options struct {
6575
// DisableRedaction indicates that fields annotated with the debug_redact
6676
// option should not be redacted from the slog.Value. When false, redacted
@@ -84,6 +94,10 @@ type options struct {
8494
// protoregistry.GlobalTypes is used. If the type cannot be found in the
8595
// resolver or if unmarshaling fails, only an "@type" field is emitted.
8696
AnyResolver protoregistry.MessageTypeResolver
97+
98+
// KeyFormatter is used to alter a [slog.Attr] key depending
99+
// on the to be logged field of a [protoreflect.Message].
100+
KeyFormatter KeyFormatter
87101
}
88102

89103
func newOptions(opts []Option) (o options) {
@@ -102,6 +116,9 @@ func mergeOptions(base, other options) (o options) {
102116
if other.AnyResolver != nil {
103117
o.AnyResolver = other.AnyResolver
104118
}
119+
if other.KeyFormatter != nil {
120+
o.KeyFormatter = other.KeyFormatter
121+
}
105122
return o
106123
}
107124

@@ -139,7 +156,11 @@ func (o options) MessageValue(msg protoreflect.Message) slog.Value {
139156
default:
140157
val = o.singularValue(field, msg.Get(field))
141158
}
142-
attrs = append(attrs, slog.Attr{Key: string(field.Name()), Value: val})
159+
key := string(field.Name())
160+
if o.KeyFormatter != nil {
161+
key = o.KeyFormatter(key, field, msg.Get(field))
162+
}
163+
attrs = append(attrs, slog.Attr{Key: key, Value: val})
143164
}
144165
return slog.GroupValue(attrs...)
145166
}

0 commit comments

Comments
 (0)