(t *testing.T)
| 36 | } |
| 37 | |
| 38 | func TestGrpcLogging(t *testing.T) { |
| 39 | ctx := context.Background() |
| 40 | info := &grpc.UnaryServerInfo{FullMethod: "Test"} |
| 41 | for _, tc := range []struct { |
| 42 | inputErr error |
| 43 | expectedErr error |
| 44 | logContains []string |
| 45 | }{{ |
| 46 | inputErr: context.Canceled, |
| 47 | expectedErr: context.Canceled, |
| 48 | logContains: []string{"level=debug", "context canceled"}, |
| 49 | }, { |
| 50 | inputErr: errors.New("yolo"), |
| 51 | expectedErr: errors.New("yolo"), |
| 52 | logContains: []string{"level=warn", "err=yolo"}, |
| 53 | }, { |
| 54 | inputErr: nil, |
| 55 | expectedErr: nil, |
| 56 | logContains: []string{"level=debug", "method=Test"}, |
| 57 | }, { |
| 58 | inputErr: DoNotLogError{Err: errors.New("yolo")}, |
| 59 | expectedErr: DoNotLogError{Err: errors.New("yolo")}, |
| 60 | logContains: nil, |
| 61 | }, { |
| 62 | inputErr: sampledError{err: errors.New("yolo"), shouldLog: true, reason: "sampled 1/10"}, |
| 63 | expectedErr: fmt.Errorf("%w (sampled 1/10)", sampledError{err: errors.New("yolo"), shouldLog: true, reason: "sampled 1/10"}), |
| 64 | logContains: []string{`err="yolo (sampled 1/10)"`}, |
| 65 | }, { |
| 66 | inputErr: sampledError{err: errors.New("yolo"), shouldLog: false, reason: "sampled 1/10"}, |
| 67 | |
| 68 | // The returned error should have the "sampled" suffix because it has been effectively sampled even if not logged. |
| 69 | expectedErr: fmt.Errorf("%w (sampled 1/10)", sampledError{err: errors.New("yolo"), shouldLog: false, reason: "sampled 1/10"}), |
| 70 | logContains: nil, |
| 71 | }} { |
| 72 | t.Run("", func(t *testing.T) { |
| 73 | buf := bytes.NewBuffer(nil) |
| 74 | logger := log.NewLogfmtLogger(buf) |
| 75 | l := GRPCServerLog{Log: logger, WithRequest: true, DisableRequestSuccessLog: false} |
| 76 | |
| 77 | handler := func(context.Context, interface{}) (interface{}, error) { |
| 78 | return nil, tc.inputErr |
| 79 | } |
| 80 | |
| 81 | _, err := l.UnaryServerInterceptor(ctx, nil, info, handler) |
| 82 | |
| 83 | if tc.expectedErr != nil { |
| 84 | require.EqualError(t, err, tc.expectedErr.Error()) |
| 85 | } else { |
| 86 | require.NoError(t, err) |
| 87 | } |
| 88 | |
| 89 | // The input error should be preserved in the chain. |
| 90 | require.ErrorIs(t, err, tc.inputErr) |
| 91 | |
| 92 | if len(tc.logContains) == 0 { |
| 93 | require.Empty(t, buf) |
| 94 | } |
| 95 | for _, content := range tc.logContains { |
nothing calls this directly
no test coverage detected