马上就要过年了,加油。
prometheus是一个非常棒的工具,结合grafana能够让我在不写代码,或者少写代码的情况下搭建一套有效的监控体系。这里介绍一下prometheus监控golang程序的方式。
要想你的程序能够被监控,你就必须要将程序运行中的各项目指标暴露出来,提供给promtheus采集信息。我们可以使用promethues提供的golang客户端暴露自身的运行时信息。代码例子如下:
package main
import (
"log"
"net/http"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
func main() {
http.Handle("/metrics", promhttp.Handler())
log.Fatal(http.ListenAndServe(":8080", nil))
}
go run main.go
访问本地的8080端口就能看到监控的指标,这里监控的都是默认指标,当然你可以可以自定义你需要的量化的指标,然后暴露出来,具体做法我不介绍了。
![9be33fb1df37466b947c069b49b7eeb6.png](https://i-blog.csdnimg.cn/blog_migrate/a9c763aa8a17ef17916d4883ff224fce.jpeg)
现在我们要配置promtheus,让他采集我们的监控指标
- job_name: 'golang'
scrape_interval: 20s
metrics_path: /metrics
static_configs:
- targets: ['localhost:8080']
启动promethues,我们golang指标就被采集到了时序数据库中,接下来就是把这些指标在grafana图形化展示出来,最后展示出来的效果如下:
![29cb8b107bb615b31ec57ba0cbfc9d5d.png](https://i-blog.csdnimg.cn/blog_migrate/39d2616487a3cd101311593a74037ba2.jpeg)
如果服务数量较多,可以考虑将服务注册到consul中去,promethues通过服务发现来采集需要监控的服务。