欢迎加入go语言学习交流群 636728449

Prometheus笔记(二)监控go项目实时给grafana展示

Prometheus笔记(一)metric type

一、prometheus和grafana安装

1、promethues安装

先写好配置文件,保存为prometheus.yml

  1. global:
  2. scrape_interval: 15s # By default, scrape targets every 15 seconds.
  3. # Attach these labels to any time series or alerts when communicating with
  4. # external systems (federation, remote storage, Alertmanager).
  5. external_labels:
  6. monitor: 'codelab-monitor'
  7. # A scrape configuration containing exactly one endpoint to scrape:
  8. # Here it's Prometheus itself.
  9. scrape_configs:
  10. # The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
  11. - job_name: 'prometheus' //服务的名称,后续要监控我们自己的服务时只需要按照这个格式再添加上
  12. # Override the global default and scrape targets from this job every 5 seconds.
  13. scrape_interval: 5s
  14. static_configs:
  15. - targets: ['localhost:9090'] //这个为服务的ip和port

更多配置文件写法请参考:https://prometheus.io/docs/operating/configuration/

官方给出供参考的配置文件:https://github.com/prometheus/prometheus/blob/release-2.3/config/testdata/conf.good.yml

然后利用docker启动。

docker run -p 9090:9090 --network=host -v /root/prometheus.yml:/etc/prometheus/prometheus.yml prom/prometheus

启动之后,可以先测试一下是否可以用。

  1. [root@localhost ~]# curl http://localhost:9090/api/v1/label/job/values
  2. {
  3. "status":"success",
  4. "data":["prometheus"]
  5. }

如果是用上面我给出来的默认配置,返回值应该是和这里给出来的一样。说明promethues服务端启动好了。

2、grafana安装

这篇文章只是演示基本用法,所以用到的grafana的配置都是默认的。直接使用下面的命令启动就可以了。

  1. $ docker run -d -p 3000:3000 grafana/grafana

如果需要更多功能则需要更复杂的配置了,更多配置方法请参考:http://docs.grafana.org/installation/docker/

docker镜像起来后,用浏览器登入 127.0.0.0:3000 ,会弹出来登入界面,用户名和密码为admin/admin,第一次会提示修改密码,按照提示操作即可。这样就完成了安装。

二、获取监控数据

这一步我主要写一个简单的go项目,用来获取内存的实时使用率数据,然后在grafana展示。

代码下载地址:https://github.com/Zhanben/goproject/tree/master/gomemory

  1. package main
  2. import (
  3. "net/http"
  4. "log"
  5. "time"
  6. "os"
  7. "github.com/prometheus/client_golang/prometheus/promhttp"
  8. "github.com/prometheus/client_golang/prometheus"
  9. "github.com/shirou/gopsutil/mem"
  10. )
  11. func main (){
  12. //初始化日志服务
  13. logger := log.New(os.Stdout, "[Memory]", log.Lshortfile | log.Ldate | log.Ltime)
  14. //初始一个http handler
  15. http.Handle("/metrics", promhttp.Handler())
  16. //初始化一个容器
  17. diskPercent := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  18. Name: "memeory_percent",
  19. Help: "memeory use percent",
  20. },
  21. []string {"percent"},
  22. )
  23. prometheus.MustRegister(diskPercent)
  24. // 启动web服务,监听1010端口
  25. go func() {
  26. logger.Println("ListenAndServe at:localhost:1010")
  27. err := http.ListenAndServe("localhost:1010", nil)
  28. if err != nil {
  29. logger.Fatal("ListenAndServe: ", err)
  30. }
  31. }()
  32. //收集内存使用的百分比
  33. for {
  34. logger.Println("start collect memory used percent!")
  35. v, err := mem.VirtualMemory()
  36. if err != nil {
  37. logger.Println("get memeory use percent error:%s", err)
  38. }
  39. usedPercent := v.UsedPercent
  40. logger.Println("get memeory use percent:", usedPercent)
  41. diskPercent.WithLabelValues("usedMemory").Set(usedPercent)
  42. time.Sleep(time.Second*2)
  43. }
  44. }

程序跑起来的输出如下:

  1. [root@localhost demoproject]# go run memory.go
  2. [Memory]2018/07/14 11:43:12 memory.go:42: start collect memory used percent!
  3. [Memory]2018/07/14 11:43:12 memory.go:48: get memeory use percent: 41.22097449562238
  4. [Memory]2018/07/14 11:43:12 memory.go:33: ListenAndServe at:locahost:1010
  5. [Memory]2018/07/14 11:43:14 memory.go:42: start collect memory used percent!
  6. [Memory]2018/07/14 11:43:14 memory.go:48: get memeory use percent: 41.219733205342514
  7. [Memory]2018/07/14 11:43:16 memory.go:42: start collect memory used percent!
  8. [Memory]2018/07/14 11:43:16 memory.go:48: get memeory use percent: 41.219733205342514
  9. ^Csignal: interrupt

此时可以查询的到promethues监控到的数据。

  1. [root@localhost ~]# curl http://localhost:1010/metrics
  2. ...
  3. # HELP go_memstats_sys_bytes Number of bytes obtained by system. Sum of all system allocations.
  4. # TYPE go_memstats_sys_bytes gauge
  5. go_memstats_sys_bytes 3.346432e+06
  6. //这个为代码添加的字段,其余为promethues默认监控字段
  7. # HELP memeory_percent memeory use percent
  8. # TYPE memeory_percent gauge
  9. memeory_percent{percent="usedMemory"} 41.16718525016137
  10. # HELP process_cpu_seconds_total Total user and system CPU time spent in seconds.
  11. # TYPE process_cpu_seconds_total counter
  12. process_cpu_seconds_total 0.01
  13. ....

三、配置grafana展示数据

1、修改配置重启promethues和grafana

先将监控服务注册到promethues服务端,修改配置文件:promethues.yml

  1. ... //和前面的配置文件一样
  2. scrape_configs:
  3. # The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
  4. - job_name: 'memory' //给你的服务取的名字
  5. # Override the global default and scrape targets from this job every 5 seconds.
  6. scrape_interval: 5s
  7. static_configs:
  8. - targets: ['localhost:1010'] //改成你自己代码里面使用的端口号

暂停掉之前启动的promethues和grafana

  1. [root@localhost ~]# docker ps
  2. CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
  3. 650cb5891e56 grafana/grafana "/run.sh" 19 hours ago Up 19 hours 0.0.0.0:3000->3000/tcp brave_ride
  4. 850a44d18dfe prom/prometheus "/bin/prometheus -..." 21 hours ago Up 21 hours 0.0.0.0:9090->9090/tcp zen_keller
  5. [root@localhost ~]# docker stop 850a44d18dfe
  6. 850a44d18dfe
  7. [root@localhost ~]# docker stop 650cb5891e56
  8. 650cb5891e56

修改好配置文件之后重新启动promethues和grafana

  1. [root@localhost ~]# docker run -d -p 9090:9090 --network=host -v /root/prometheus.yml:/etc/prometheus/prometheus.yml prom/prometheus
  2. [root@localhost ~]# docker run -d -p 3000:3000 grafana/grafana

检验promethues服务端是否注册到了我们自己的服务。

  1. [root@localhost demoproject]# curl http://localhost:9090/api/v1/targets
  2. {
  3. "status": "success",
  4. "data": {
  5. "activeTargets": [{
  6. "discoveredLabels": {
  7. "__address__": "localhost:1010",
  8. "__metrics_path__": "/metrics",
  9. "__scheme__": "http",
  10. "job": "memory"
  11. },
  12. "labels": {
  13. "instance": "localhost:1010",
  14. "job": "memory"
  15. //这个memory即我们在promethues的配置文件填写的名字
  16. },
  17. "scrapeUrl": "http://localhost:1010/metrics",
  18. "lastError": "",
  19. "lastScrape": "2018-07-14T07:39:26.127284982Z",
  20. "health": "up"
  21. //注意上面这个字段要为up,要不然后续grafana查询不到数据
  22. }
  23. ],
  24. "droppedTargets": []
  25. }
  26. }

2、创建数据源

  • 打开grafana界面,登入后如下图所示:

  • 创建数据源



    按照图片里面的填写的填好。其中memory为数据源名字,可以自己随便取一个。类型需要选择promethues。下面的URL需要填写promethues的服务端的URL,access选择不使用代理的Browser。填好之后点击下面的保存,完成创建数据源。

3、创建dashboard

第一步如图所示,按照图中的三步操作。



操作完成之后会进入下图所示的界面,然后再次按照图中提示操作即可。



完成之后会弹出来一个panle,单击下拉框,点击Edit。



点击Edit之后会pane下方会得到下图展示的界面:



在查询字段的地方填入,代码缩写的字段prometheus.NewGaugeVec创建时填写的name字段,本示例代码为memory_percent。填好之后点击下option旁边的query inspector,就可以在上面的表中查看到数据了。

最后查询到的数据如下图所示:

欢迎加入go语言学习交流群 636728449

参考资料

1、 https://godoc.org/github.com/prometheus/client_golang/prometheus

2、 https://prometheus.io/docs/introduction/overview/

Prometheus笔记(二)监控go项目实时给grafana展示的更多相关文章

  1. python 学习笔记二十 django项目bbs论坛

    项目:开发一个简单的BBS论坛 需求: 整体参考“抽屉新热榜” + “虎嗅网” 实现不同论坛版块 帖子列表展示 帖子评论数.点赞数展示 在线用户展示 允许登录用户发贴.评论.点赞 允许上传文件 帖子可 ...

  2. SpringCloud笔记二:搭建项目基础框架

    目录 搭建框架 新建父工程 新建子工程api 新建子工程提供者provider 新建消费者consumer 总结 搭建框架 我们的SpringCloud微服务框架是父子工程,有一个父工程,剩下的都是子 ...

  3. Beego 学习笔记二:第一个项目

    第一个MVC项目 1>     使用beego命令,创建一个项目 首先切换到创建项目的位置,输入bee new firstweb命令,创建成功之后会出现一个名为firstweb的文件夹 2> ...

  4. Prometheus笔记(一)metric type

    欢迎加入go语言学习交流群 636728449 Prometheus笔记(二)监控go项目实时给grafana展示 Prometheus笔记(一)metric type 文章目录 Prometheus ...

  5. Prometheus监控学习笔记之360基于Prometheus的在线服务监控实践

    0x00 初衷 最近参与的几个项目,无一例外对监控都有极强的要求,需要对项目中各组件进行详细监控,如服务端API的请求次数.响应时间.到达率.接口错误率.分布式存储中的集群IOPS.节点在线情况.偏移 ...

  6. amazeui学习笔记二(进阶开发1)--项目结构structure

    amazeui学习笔记二(进阶开发1)--项目结构structure 一.总结 1.项目结构:是说的amazeui在github上面的项目结构,二次开发amazeui用 二.项目结构structure ...

  7. prometheus监控java项目(jvm等):k8s外、k8s内

    前言 虽然可以使用jvisualvm之类的工具监控java项目,但是集群环境下,还是捉襟见肘,下面介绍如何用主流的prometheus来监控java项目. java项目配置 在pom.xml中添加依赖 ...

  8. Grafana+Prometheus通过node_exporter监控Linux服务器信息

    Grafana+Prometheus通过node_exporter监控Linux服务器信息 一.Grafana+Prometheus通过node_exporter监控Linux服务器信息 1.1nod ...

  9. mysql颠覆实战笔记(二)-- 用户登录(一):唯一索引的妙用

    版权声明:笔记整理者亡命小卒热爱自由,崇尚分享.但是本笔记源自www.jtthink.com(程序员在囧途)沈逸老师的<web级mysql颠覆实战课程 >.如需转载请尊重老师劳动,保留沈逸 ...

随机推荐

  1. LCD 调试总结

    (1) 液晶显示模式 并行:MCU接口.RGB接口.Vysnc接口 串行:SPI接口.MDDI接口 (2) 屏幕颜色 实质上即为色阶的概念.色阶是表示手机液晶显示屏亮度强弱的指数标准,也就是通常所说的 ...

  2. zookeeper集群模式安装

    服务器节点规划: 节点1:192.168.0.103 节点2:192.168.0.104 节点3:192.168.0.105 安装zookeeper,将zookeeper上传到三个服务器,保存在/ho ...

  3. Python类属性与实例属性理解

    按理讲,类属性改变,类的实例对象这个属性也应该被改变,但是在python中实际却不是这样 class test(): name = 111 a = test() b = test() a.name = ...

  4. Hibernate的多对多关系

    1.表的关系: 分别有三个表:课程表.学生表.分数表.课程和学生的关系是多对多的,因为一个学生对应多个课程,而一个课程被多个学生选修.如果用一对多.多对一的观点来看待课程和学生的关系显然是不对的,因为 ...

  5. .NET进阶篇06-async异步、thread多线程2

    知识需要不断积累.总结和沉淀,思考和写作是成长的催化剂 内容目录 一.线程Thread1.生命周期2.后台线程3.静态方法1.线程本地存储2.内存栅栏4.返回值二.线程池ThreadPool1.工作队 ...

  6. redis集群节点重启后恢复

    服务器重启后,集群报错: [root@SHH-HQ-NHS11S nhsuser]# redis-cli -c -h ip -p 7000ip:7000> set cc dd(error) CL ...

  7. 回声消除中的LMS和NLMS算法与MATLAB实现

    自适应滤波是数字信号处理的核心技术之一,在科学和工业上有着广泛的应用领域.自适应滤波技术应用广泛,包括回波抵消.自适应均衡.自适应噪声抵消和自适应波束形成.回声对消是当今通信系统中普遍存在的现象.声回 ...

  8. ffmpeg 编译安装

    1.FFmpeg编译 1.1.安装yasm 这里我是直接通过ubuntu包安装的,当然也可以通过编译源码来安装. sudo apt-get install yasm 1.2.下载FFmpeg git ...

  9. suseoj 1208: 排列问题 (STL, next_permutation(A.begin(), A.end()))

    1208: 排列问题 时间限制: 1 Sec  内存限制: 128 MB提交: 2  解决: 2[提交][状态][讨论版][命题人:liyuansong] 题目描述 全排列的生成就是对于给定的字符集或 ...

  10. mysql定时任务(event事件)

    1.event事件 事件(event)是MySQL在相应的时刻调用的过程式数据库对象.一个事件可调用一次,也可周期性的启动,它由一个特定的线程来管理的,也就是所谓的“事件调度器” 事件和触发器类似,都 ...