-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathcontext.go
More file actions
40 lines (31 loc) · 763 Bytes
/
context.go
File metadata and controls
40 lines (31 loc) · 763 Bytes
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
37
38
39
40
package httplog
import (
"context"
"log/slog"
)
const (
ErrorKey = "error"
)
type ctxKeyLogAttrs struct{}
func (c *ctxKeyLogAttrs) String() string {
return "httplog attrs context"
}
// SetAttrs sets the attributes on the request log.
func SetAttrs(ctx context.Context, attrs ...slog.Attr) {
if ptr, ok := ctx.Value(ctxKeyLogAttrs{}).(*[]slog.Attr); ok && ptr != nil {
*ptr = append(*ptr, attrs...)
}
}
func getAttrs(ctx context.Context) []slog.Attr {
if ptr, ok := ctx.Value(ctxKeyLogAttrs{}).(*[]slog.Attr); ok && ptr != nil {
return *ptr
}
return nil
}
// SetError sets the error attribute on the request log.
func SetError(ctx context.Context, err error) error {
if err != nil {
SetAttrs(ctx, slog.Any(ErrorKey, err))
}
return err
}