go micro metrics 接入Prometheus、Grafana

舞林

本文介绍go micro中加入metric, 并接入Prometheus、Grafana

1.go micro中间件加载prometheus plugins

go micro中提供了prometheus plugins

github.com/micro/go-plugins/wrapper/monitoring/prometheus/

package main

import (
    "net/http"
    "github.com/micro/go-plugins/wrapper/monitoring/prometheus/v2"
    "github.com/prometheus/client_golang/prometheus/promhttp"
    //...
)

func main() {
    // New Service
    service := micro.NewService(
        micro.Name("go.micro.api.myauth"),
        micro.Version("latest"),
        micro.WrapHandler(prometheus.NewHandlerWrapper()),
    )

    // Initialise service
    service.Init(
        // create wrap for the Myauth service client
        micro.WrapHandler(client.MyauthWrapper(service)),
    )
    go PrometheusBoot()
    
    // Register Handler
    myauth.RegisterMyauthHandler(service.Server(), new(handler.Myauth))

    // Run service
    if err := service.Run(); err != nil {
        log.Fatal(err)
    }
}

func PrometheusBoot() {
    http.Handle("/metrics", promhttp.Handler())
    // 启动web服务,监听8085端口
    go func() {
        err := http.ListenAndServe("localhost:8085", nil)
        if err != nil {
            log.Fatal("ListenAndServe: ", err)
        }
    }()
}

代码很简单,在micro.NewService中传入micro.WrapHandler(prometheus.NewHandlerWrapper()),

再启动web服务,监听8085端口,暴露metric数据

访问http://localhost:8085/metrics即可看到数据

image

2.启动prometheus

本文演示prometheus、grafana在docker中运行

启动prometheus

  1. 创建prometheus.yml,粘贴以下内容
global:
  scrape_interval:     15s # By default, scrape targets every 15 seconds.

  # Attach these labels to any time series or alerts when communicating with
  # external systems (federation, remote storage, Alertmanager).
  external_labels:
    monitor: 'codelab-monitor'

# A scrape configuration containing exactly one endpoint to scrape:
# Here it's Prometheus itself.
scrape_configs:
  # The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
  - job_name: 'prometheus'
    # Override the global default and scrape targets from this job every 5 seconds.
    scrape_interval: 5s
    static_configs:
      - targets: ['host.docker.internal:8085']

这里示例 micro 微服务直接运行在宿主机上,Prometheus抓取数据需要访问主机端口,所以targets的ip写的是host.docker.internal

  1. 启动prometheus

docker run -d -p 9090:9090 -v /Users/wulin/gowork/myauth/prometheus.yml:/etc/prometheus/prometheus.yml --name prometheus prom/prometheus

访问地址http://localhost:9090/

image
可以看到抓取状态是正常的

2.启动grafana

docker run -d -p 3000:3000 grafana/grafana
访问地址http://localhost:3000/

首先设置数据源,选择prometheus,url填http://宿主ip:9090/ ,点击保存,提示成功即可

image

dashboard中点击`add panel`, 选择数据源,填写metrics(点击有提示),完成后点`apply`即可
image
测试用的node-exporter,可以用于测试

docker run -d  -p 9100:9100 \
  -v "/proc:/host/proc:ro" \
  -v "/sys:/host/sys:ro" \
  -v "/:/rootfs:ro" \
  prom/node-exporter

以上内容讨论的是 go micro 的metrics,

以下内容讨论的是micro网关中的metrics,官方plugins请见https://github.com/micro/go-p...

自定义 micro 网关 代码如下,仅列出metrics相关代码

import (

    "github.com/micro/go-plugins/micro/metrics/v2"
    "github.com/micro/micro/v2/cmd"
    "github.com/micro/micro/v2/plugin"
)

func main() {
    plugin.Register(metrics.NewPlugin())
    cmd.Init()
}

插件中代码如下

// NewPlugin returns a new metrics plugin
func NewPlugin() plugin.Plugin {
    metrics := new(Metrics)

    return plugin.NewPlugin(
        plugin.WithName("metrics"),
        plugin.WithFlag(
            &cli.StringFlag{
                Name:  "metrics",
                Usage: "Specify the type of metrics provider e.g prometheus",
            },
        ),
        plugin.WithHandler(metrics.Handler),
        plugin.WithInit(func(ctx *cli.Context) error {
            provider := ctx.String("metrics")

            switch provider {
            case "prometheus":
                metrics.Provider = prometheus.New()
                log.Info("Loaded prometheus metrics at /metrics")
            }

            return nil
        }),
    )
}

看起来不是很完善,目前只支持prometheus,且参数不能在代码指定metrics ,启动如下

go run ./gateway/main.go -metrics prometheus api --handler=api

plugins参数指定需要放到api之前哦

启动后可以看见控制台

file=v2@v2.9.1/metrics.go:49 level=info Loaded prometheus metrics at /metrics

访问http://localhost:8080/metrics ,即可看到metrics信息

数据收集展现和上文一样,这里就不重复介绍了。
image
image
image

go micro 分析系列文章
go micro server 启动分析
go micro client
go micro broker
go micro cmd
go micro config
go micro store
go micro registry
go micro router
go micro runtime
go micro transport
go micro web
go micro registry 插件consul
go micro plugin
go micro jwt 网关鉴权
go micro 链路追踪
go micro 熔断与限流
go micro wrapper 中间件
go micro metrics 接入Prometheus、Grafana

阅读 1.2k

舞林
关注web安全,某工地php搬砖工一只

漫步风雨中

1.5k 声望
28 粉丝
0 条评论
你知道吗?

漫步风雨中

1.5k 声望
28 粉丝
宣传栏