dubbo.apache.org/dubbo-go/v3@v3.1.1/filter/metrics/filter.go (about) 1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 18 package metrics 19 20 import ( 21 "context" 22 "time" 23 ) 24 25 import ( 26 "dubbo.apache.org/dubbo-go/v3/common/constant" 27 "dubbo.apache.org/dubbo-go/v3/common/extension" 28 "dubbo.apache.org/dubbo-go/v3/filter" 29 "dubbo.apache.org/dubbo-go/v3/metrics" 30 "dubbo.apache.org/dubbo-go/v3/metrics/rpc" 31 "dubbo.apache.org/dubbo-go/v3/protocol" 32 ) 33 34 // must initialize before using the filter and after loading configuration 35 var metricFilterInstance *metricsFilter 36 37 func init() { 38 extension.SetFilter(constant.MetricsFilterKey, newFilter) 39 } 40 41 // metricsFilter will report RPC metrics to the metrics bus and implements the filter.Filter interface 42 type metricsFilter struct{} 43 44 // Invoke publish the BeforeInvokeEvent and AfterInvokeEvent to metrics bus 45 func (mf *metricsFilter) Invoke(ctx context.Context, invoker protocol.Invoker, invocation protocol.Invocation) protocol.Result { 46 metrics.Publish(rpc.NewBeforeInvokeEvent(invoker, invocation)) 47 start := time.Now() 48 res := invoker.Invoke(ctx, invocation) 49 end := time.Now() 50 duration := end.Sub(start) 51 metrics.Publish(rpc.NewAfterInvokeEvent(invoker, invocation, duration, res)) 52 return res 53 } 54 55 // OnResponse do nothing and return the result 56 func (mf *metricsFilter) OnResponse(ctx context.Context, res protocol.Result, invoker protocol.Invoker, invocation protocol.Invocation) protocol.Result { 57 return res 58 } 59 60 // newFilter creates a new metricsFilter instance. 61 // 62 // It's lazy initialization, 63 // and make sure that the configuration had been loaded before invoking this method. 64 func newFilter() filter.Filter { 65 if metricFilterInstance == nil { 66 metricFilterInstance = &metricsFilter{} 67 } 68 return metricFilterInstance 69 }