OSDN Git Service

new repo
[bytom/vapor.git] / vendor / github.com / go-kit / kit / examples / addsvc / pkg / addendpoint / middleware.go
1 package addendpoint
2
3 import (
4         "context"
5         "fmt"
6         "time"
7
8         "github.com/go-kit/kit/endpoint"
9         "github.com/go-kit/kit/log"
10         "github.com/go-kit/kit/metrics"
11 )
12
13 // InstrumentingMiddleware returns an endpoint middleware that records
14 // the duration of each invocation to the passed histogram. The middleware adds
15 // a single field: "success", which is "true" if no error is returned, and
16 // "false" otherwise.
17 func InstrumentingMiddleware(duration metrics.Histogram) endpoint.Middleware {
18         return func(next endpoint.Endpoint) endpoint.Endpoint {
19                 return func(ctx context.Context, request interface{}) (response interface{}, err error) {
20
21                         defer func(begin time.Time) {
22                                 duration.With("success", fmt.Sprint(err == nil)).Observe(time.Since(begin).Seconds())
23                         }(time.Now())
24                         return next(ctx, request)
25
26                 }
27         }
28 }
29
30 // LoggingMiddleware returns an endpoint middleware that logs the
31 // duration of each invocation, and the resulting error, if any.
32 func LoggingMiddleware(logger log.Logger) endpoint.Middleware {
33         return func(next endpoint.Endpoint) endpoint.Endpoint {
34                 return func(ctx context.Context, request interface{}) (response interface{}, err error) {
35
36                         defer func(begin time.Time) {
37                                 logger.Log("transport_error", err, "took", time.Since(begin))
38                         }(time.Now())
39                         return next(ctx, request)
40
41                 }
42         }
43 }