disable prometheus if not configured (#663)

This commit is contained in:
Kevin Wan
2021-04-30 15:09:49 +08:00
committed by GitHub
parent 9adc7d4cb9
commit 06eeef2cf3
7 changed files with 79 additions and 9 deletions

View File

@@ -6,6 +6,7 @@ import (
"time"
"github.com/tal-tech/go-zero/core/metric"
"github.com/tal-tech/go-zero/core/prometheus"
"github.com/tal-tech/go-zero/core/timex"
"google.golang.org/grpc"
"google.golang.org/grpc/status"
@@ -36,6 +37,10 @@ var (
func UnaryPrometheusInterceptor() grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (
interface{}, error) {
if !prometheus.Enabled() {
return handler(ctx, req)
}
startTime := timex.Now()
resp, err := handler(ctx, req)
metricServerReqDur.Observe(int64(timex.Since(startTime)/time.Millisecond), info.FullMethod)

View File

@@ -5,10 +5,25 @@ import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/tal-tech/go-zero/core/prometheus"
"google.golang.org/grpc"
)
func TestUnaryPromMetricInterceptor(t *testing.T) {
func TestUnaryPromMetricInterceptor_Disabled(t *testing.T) {
interceptor := UnaryPrometheusInterceptor()
_, err := interceptor(context.Background(), nil, &grpc.UnaryServerInfo{
FullMethod: "/",
}, func(ctx context.Context, req interface{}) (interface{}, error) {
return nil, nil
})
assert.Nil(t, err)
}
func TestUnaryPromMetricInterceptor_Enabled(t *testing.T) {
prometheus.StartAgent(prometheus.Config{
Host: "localhost",
Path: "/",
})
interceptor := UnaryPrometheusInterceptor()
_, err := interceptor(context.Background(), nil, &grpc.UnaryServerInfo{
FullMethod: "/",