Skip to content

Commit

Permalink
🚧 wip: add AccessLogInterceptor (UnaryInterceptor)
Browse files Browse the repository at this point in the history
Signed-off-by: Rintaro Okamura <[email protected]>
  • Loading branch information
rinx committed Nov 25, 2020
1 parent b3a8d01 commit f7dcc29
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 1 deletion.
63 changes: 63 additions & 0 deletions internal/net/grpc/interceptor.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,11 @@ package grpc

import (
"context"
"path"
"time"

"github.com/vdaas/vald/internal/log"
"github.com/vdaas/vald/internal/observability/trace"
"github.com/vdaas/vald/internal/safety"
"google.golang.org/grpc"
)
Expand Down Expand Up @@ -61,3 +65,62 @@ func RecoverStreamInterceptor() StreamServerInterceptor {
})()
}
}

func AccessLogInterceptor() UnaryServerInterceptor {
return func(
ctx context.Context,
req interface{},
info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler,
) (resp interface{}, err error) {
var traceID string

span := trace.FromContext(ctx)
if span != nil {
traceID = span.SpanContext().TraceID.String()
}

start := time.Now()

resp, err = handler(ctx, req)

latency := float64(time.Since(start)) / float64(time.Second)
startTime := float64(start.UnixNano()) / float64(time.Second)

service, method := parseMethod(info.FullMethod)

if err != nil {
log.Error(
"rpc call proceeded",
map[string]interface{}{
"grpcService": service,
"grpcMethod": method,
"startTime": startTime,
"latency": latency,
"traceID": traceID,
"error": err,
},
)
} else {
log.Info(
"rpc call proceeded",
map[string]interface{}{
"grpcService": service,
"grpcMethod": method,
"startTime": startTime,
"latency": latency,
"traceID": traceID,
},
)
}

return resp, err
}
}

func parseMethod(fullMethod string) (service, method string) {
service = path.Dir(fullMethod)[1:]
method = path.Base(fullMethod)

return service, method
}
5 changes: 4 additions & 1 deletion pkg/agent/core/ngt/usecase/agentd.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,10 @@ func New(cfg *config.Data) (r runner.Runner, err error) {
agent.RegisterAgentServer(srv, g)
}),
server.WithGRPCOption(
grpc.ChainUnaryInterceptor(grpc.RecoverInterceptor()),
grpc.ChainUnaryInterceptor(
grpc.RecoverInterceptor(),
grpc.AccessLogInterceptor(),
),
grpc.ChainStreamInterceptor(grpc.RecoverStreamInterceptor()),
),
server.WithPreStartFunc(func() error {
Expand Down

0 comments on commit f7dcc29

Please sign in to comment.