首页 > 其他分享 >9.【go-kit教程】go-kit集成Prometheus

9.【go-kit教程】go-kit集成Prometheus

时间:2023-02-25 22:12:55浏览次数:43  
标签:http prometheus kit Prometheus func go httptransport

  • 在 Go kit 中集成 Prometheus 进行 API 监控可以帮助开发人员更好地了解系统的性能和行为,提高系统的可观察性和可靠性。下面是一个简单的示例,演示如何在 Go kit 中集成 Prometheus 进行 API 监控:

    package main
    
    import (
    	"net/http"
    
    	"github.com/go-kit/kit/log"
    	"github.com/go-kit/kit/metrics/prometheus"
    	"github.com/go-kit/kit/metrics/provider"
    	"github.com/go-kit/kit/transport"
    	httptransport "github.com/go-kit/kit/transport/http"
    	"github.com/prometheus/client_golang/prometheus/promhttp"
    )
    
    func main() {
    	// 创建 Prometheus 监控器
    	fieldKeys := []string{"method", "error"}
    	requestCount := prometheus.NewCounterFrom(provider.NewProvider(), prometheus.CounterOpts{
    		Namespace: "my_api",
    		Name:      "request_count",
    		Help:      "Number of requests received.",
    	}, fieldKeys)
    	requestLatency := prometheus.NewSummaryFrom(provider.NewProvider(), prometheus.SummaryOpts{
    		Namespace: "my_api",
    		Name:      "request_latency",
    		Help:      "Total duration of requests in microseconds.",
    	}, fieldKeys)
    
    	// 创建 endpoint
    	helloEndpoint := func() string {
    		return "Hello, World!"
    	}
    	helloEndpoint = transport.NewServer(
    		helloEndpoint,
    		func(ctx context.Context, r *http.Request) (interface{}, error) {
    			return nil, nil
    		},
    		func(ctx context.Context, w http.ResponseWriter, response interface{}) error {
    			w.Header().Set("Content-Type", "text/plain; charset=utf-8")
    			fmt.Fprint(w, response.(string))
    			return nil
    		},
    		transport.ServerErrorLogger(log.NewNopLogger()),
    		transport.ServerErrorEncoder(errorEncoder),
    		transport.ServerBefore(prometheus.HTTPToContext()),
    	).Endpoint()
    
    	// 创建 HTTP server
    	r := mux.NewRouter()
    	r.Handle("/hello", httptransport.NewServer(
    		helloEndpoint,
    		httpDecodeRequest,
    		httpEncodeResponse,
    		httptransport.ServerBefore(prometheus.HTTPToContext()),
    		httptransport.ServerErrorLogger(log.NewNopLogger()),
    		httptransport.ServerErrorEncoder(errorEncoder),
    		httptransport.ServerBefore(prometheus.HTTPToContext()),
    	)).Methods("GET")
    	r.Handle("/metrics", promhttp.Handler())
    
    	fmt.Println("listening on :8080...")
    	http.ListenAndServe(":8080", r)
    }
    
    func httpDecodeRequest(_ context.Context, r *http.Request) (interface{}, error) {
    	return nil, nil
    }
    
    func httpEncodeResponse(_ context.Context, w http.ResponseWriter, response interface{}) error {
    	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
    	fmt.Fprint(w, response.(string))
    	return nil
    }
    
    func errorEncoder(_ context.Context, err error, w http.ResponseWriter) {
    	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
    	w.WriteHeader(http.StatusBadRequest)
    	fmt.Fprint(w, err.Error())
    }
    
    

标签:http,prometheus,kit,Prometheus,func,go,httptransport
From: https://www.cnblogs.com/bigox/p/17155565.html

相关文章

  • 使用Go语言编写邮件内容解析功能
    保存为readmsg.gopackagemainimport("bytes""database/sql""encoding/base64""encoding/json""io""io/ioutil""log""mime"......
  • Chrome插件:Chrome-Sync-Helper 使用google搜索
    解决墙的原因,无法使用google搜索找到插件 https://www.zhihu.com/question/387679779/answer/2822702411?utm_campaign=shareopn&utm_medium=social&utm_oi=7318067228......
  • 已解决(MongoDB安装报错)Service ‘MongoDB Server (MongoDB)’ (MongoDB) failed tosta
     报错问题粉丝群里面的一个小伙伴想安装MongoDB但是发生了报错(当时他心里瞬间凉了一大截,跑来找我求助,然后顺利帮助他解决了,顺便记录一下希望可以帮助到更多遇到这个bug......
  • Go从入门到精通——常见报错: C compiler "gcc" not found: exec: "gcc": executable f
    常见报错:Ccompiler"gcc"notfound:exec:"gcc":executablefilenotfoundin%PATH%一、背景操作系统:windows10专业版Go版本:goversiongo1.19.4windows/a......
  • go依赖管理
    原始依赖管理方式1.Go语言可以利用本身的能力做基础依赖管理,几个重要的组件包括GOPATH工作目录,Go命令工具(getinstallbuild)等,通过goget下载依赖包的最新版本到GOPATH......
  • 2023最新MongoDB规范
    前言MongoDB是非关系型数据库的典型代表,DB-EnginesRanking数据显示,近年来,MongoDB在NoSQL领域一直独占鳌头。MongoDB是为快速开发互联网应用而设计的数据库系统,其数据模......
  • Go语言中密码加密校验
    使用go自带的库bcryptbcrypt是不可逆的加密算法,无法通过解密密文得到明文。bcrypt和其他对称或非对称加密方式不同的是,不是直接解密得到明文,也不是二次加密比较密文,而是......
  • golang中的close函数
    close函数是用于关闭通道的。官方解释(摘自close函数源代码注释):Theclosebuilt-infunctionclosesachannel,whichmustbeeitherbidirectionalorsend-only.Itsho......
  • golang 日志
    packagelogimport( "NOONASN/global" "github.com/natefinch/lumberjack" "go.uber.org/zap" "go.uber.org/zap/zapcore" "os" "path" "path/filepath")func......
  • 在Google的TPU上训练Fashion MNIST图像识别模型
    作者|张强今天我们要训练的模型是基于Keras框架,来训练FashionMNIST图像识别模型,该模型和MNIST是一样的分类数量。​​MNIST​​​的分类是0到9的十个数字​​​FashionMN......