github.com/tickoalcantara12/micro/v3@v3.0.0-20221007104245-9d75b9bcbab9/service/metrics/wrapper/wrapper.go (about) 1 // Licensed under the Apache License, Version 2.0 (the "License"); 2 // you may not use this file except in compliance with the License. 3 // You may obtain a copy of the License at 4 // 5 // https://www.apache.org/licenses/LICENSE-2.0 6 // 7 // Unless required by applicable law or agreed to in writing, software 8 // distributed under the License is distributed on an "AS IS" BASIS, 9 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 // See the License for the specific language governing permissions and 11 // limitations under the License. 12 // 13 // Original source: github.com/tickoalcantara12/micro/v3/metrics/wrapper/metrics_wrapper.go 14 15 package wrapper 16 17 import ( 18 "time" 19 20 "context" 21 22 "github.com/tickoalcantara12/micro/v3/service/metrics" 23 "github.com/tickoalcantara12/micro/v3/service/server" 24 ) 25 26 // Wrapper provides a HandlerFunc for metrics.Reporter implementations: 27 type Wrapper struct { 28 reporter metrics.Reporter 29 } 30 31 // New returns a *Wrapper configured with the given metrics.Reporter: 32 func New(reporter metrics.Reporter) *Wrapper { 33 return &Wrapper{ 34 reporter: reporter, 35 } 36 } 37 38 // HandlerFunc instruments handlers registered to a service: 39 func (w *Wrapper) HandlerFunc(handlerFunction server.HandlerFunc) server.HandlerFunc { 40 return func(ctx context.Context, req server.Request, rsp interface{}) error { 41 42 // Build some tags to describe the call: 43 tags := metrics.Tags{ 44 "method": req.Method(), 45 } 46 47 // Start the clock: 48 callTime := time.Now() 49 50 // Run the handlerFunction: 51 err := handlerFunction(ctx, req, rsp) 52 53 // Add a result tag: 54 if err != nil { 55 tags["result"] = "failure" 56 } else { 57 tags["result"] = "success" 58 } 59 60 // Instrument the result (if the DefaultClient has been configured): 61 w.reporter.Timing("service.handler", time.Since(callTime), tags) 62 63 return err 64 } 65 }