-
Notifications
You must be signed in to change notification settings - Fork 1
/
twirp.go
79 lines (62 loc) · 1.42 KB
/
twirp.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package elephantine
import (
"context"
"errors"
"github.com/twitchtv/twirp"
"golang.org/x/exp/slog"
)
func IsTwirpErrorCode(err error, code twirp.ErrorCode) bool {
if err == nil {
return false
}
var te twirp.Error
if errors.As(err, &te) {
return te.Code() == code
}
return false
}
func LoggingHooks(
logger *slog.Logger, scopesFunc func(context.Context) string,
) *twirp.ServerHooks {
hooks := twirp.ServerHooks{
RequestRouted: func(ctx context.Context) (context.Context, error) {
service, ok := twirp.ServiceName(ctx)
if ok {
SetLogMetadata(ctx, LogKeyService, service)
}
method, ok := twirp.MethodName(ctx)
if ok {
SetLogMetadata(ctx, LogKeyMethod, method)
}
return ctx, nil
},
Error: func(ctx context.Context, err twirp.Error) context.Context {
code := err.Code()
status := twirp.ServerHTTPStatusFromErrorCode(err.Code())
args := []any{
LogKeyErrorCode, code,
LogKeyError, err.Msg(),
LogKeyStatusCode, status,
}
meta := err.MetaMap()
if meta != nil {
args = append(args,
LogKeyErrorMeta, err.MetaMap())
}
if code == twirp.PermissionDenied {
args = append(args,
LogKeyScopes, scopesFunc(ctx))
}
level := slog.LevelWarn
switch {
case status == 400:
level = slog.LevelInfo
case status >= 500:
level = slog.LevelError
}
logger.Log(ctx, level, "error response", args...)
return ctx
},
}
return &hooks
}