github.com/kaydxh/golang@v0.0.131/pkg/middleware/http-middleware/monitor/opentelemetry/metric.interceptor.go (about)

     1  package interceptoropentelemetry
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  
     7  	http_ "github.com/kaydxh/golang/go/net/http"
     8  	time_ "github.com/kaydxh/golang/go/time"
     9  	logs_ "github.com/kaydxh/golang/pkg/logs"
    10  	resource_ "github.com/kaydxh/golang/pkg/middleware/resource"
    11  )
    12  
    13  func Metric(next http.Handler) http.Handler {
    14  	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    15  
    16  		tc := time_.New(true)
    17  		next.ServeHTTP(w, r)
    18  
    19  		ctx := r.Context()
    20  		calleeMethod := fmt.Sprintf("%v %v", r.Method, r.URL.Path)
    21  		resource_.ReportMetric(ctx,
    22  			resource_.Dimension{
    23  				CalleeMethod: calleeMethod,
    24  				Error:        nil,
    25  			},
    26  			tc.Elapse(),
    27  		)
    28  		tc.Tick(calleeMethod)
    29  
    30  		logger := logs_.GetLogger(ctx)
    31  		peerAddr, _ := http_.GetIPFromRequest(r)
    32  		summary := func() {
    33  			logger.WithField("cost", tc.String()).Infof(
    34  				"called by peer addr: %v",
    35  				peerAddr.String(),
    36  			)
    37  		}
    38  		defer summary()
    39  	})
    40  
    41  }