File: grpc_log.go

package info (click to toggle)
vagrant 2.3.7%2Bgit20230731.5fc64cde%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 17,616 kB
  • sloc: ruby: 111,820; sh: 462; makefile: 123; ansic: 34; lisp: 1
file content (56 lines) | stat: -rw-r--r-- 1,403 bytes parent folder | download | duplicates (3)
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
package serverclient

import (
	"context"
	"time"

	"github.com/hashicorp/go-hclog"
	"google.golang.org/grpc"
)

// logUnaryInterceptor returns a gRPC unary interceptor that inserts a hclog.Logger
// into the request context.
//
// Additionally, logUnaryInterceptor logs request and response metadata. If verbose
// is set to true, the request and response attributes are logged too.
func logClientUnaryInterceptor(logger hclog.Logger, verbose bool) grpc.UnaryClientInterceptor {
	return func(
		ctx context.Context,
		method string,
		req interface{},
		reply interface{},
		cc *grpc.ClientConn,
		invoker grpc.UnaryInvoker,
		opts ...grpc.CallOption) error {
		start := time.Now()

		// Log the request.
		{
			var reqLogArgs []interface{}
			// Log the request's attributes only if verbose is set to true.
			if verbose {
				reqLogArgs = append(reqLogArgs, "request", req)
			}
			logger.Info(method+" request", reqLogArgs...)
		}

		// Invoke the handler.
		ctx = hclog.WithContext(ctx, logger)
		err := invoker(ctx, method, req, reply, cc, opts...)

		// Log the response.
		{
			respLogArgs := []interface{}{
				"error", err,
				"duration", time.Since(start).String(),
			}
			// Log the response's attributes only if verbose is set to true.
			if verbose {
				respLogArgs = append(respLogArgs, "response", reply)
			}
			logger.Info(method+" response", respLogArgs...)
		}

		return err
	}
}