forked from btcsuite/btclog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathattrs.go
36 lines (29 loc) · 900 Bytes
/
attrs.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package btclog
import (
"context"
"encoding/hex"
"log/slog"
)
// Hex is a convenience function for a hex-encoded log attributes.
func Hex(key string, value []byte) slog.Attr {
h := hex.EncodeToString(value)
return slog.String(key, h)
}
type attrsKey struct{}
// WithCtx returns a copy of the context with which the logging attributes are
// associated.
//
// Usage:
//
// ctx := log.WithCtx(ctx, "height", 1234)
// ...
// log.Info(ctx, "Height processed") // Will contain attribute: height=1234
func WithCtx(ctx context.Context, attrs ...any) context.Context {
return context.WithValue(ctx, attrsKey{}, mergeAttrs(ctx, attrs))
}
// mergeAttrs returns the attributes from the context merged with the provided attributes.
func mergeAttrs(ctx context.Context, attrs []any) []any {
resp, _ := ctx.Value(attrsKey{}).([]any) // We know the type.
resp = append(resp, attrs...)
return resp
}