Nginx添加Prometheus监控模块nginx-lua-prometheus

Nginx添加Prometheus监控模块nginx-lua-prometheus

 前言

nginx-lua-prometheus是为专为nginx设计的Prometheus监控脚本,使用lua开发,所以需要nginx支持lua插件运行,关于如何让nginx支持lua这里就不说了,网上很容易搜到教程。

nginx-lua-prometheus目前网络上我见过两个版本,一个比较新的,一个比较古老的,比较新的尝试后发现存在不兼容问题,我的nginx版本是1.14,后来使用了比较老的版本,不过功能相似。

github地址:https://github.com/jialj/nginx-lua-prometheus

 

Nginx添加nginx-lua-prometheus

1.在server模块下面添加下面的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

lua_shared_dict prometheus_metrics 10M;
lua_package_path “你的lua文件目录/prometheus.lua”;

init_by_lua ‘
  prometheus = require(“prometheus”).init(“prometheus_metrics”)
  metric_requests = prometheus:counter(
    “nginx_http_requests_total”, “Number of HTTP requests”, {“host”, “status”})
  metric_latency = prometheus:histogram(
    “nginx_http_request_duration_seconds”, “HTTP request latency”, {“host”})
  metric_connections = prometheus:gauge(
    “nginx_http_connections”, “Number of HTTP connections”, {“state”})
  metric_requests_uri = prometheus:counter(
                “nginx_http_requests_uri_total”, “Number of HTTP requests_uri”, {“host”,”uri”, “status”, “method”})
‘;
log_by_lua ‘
  metric_requests:inc(1, {ngx.var.server_name, ngx.var.status})
  metric_latency:observe(tonumber(ngx.var.request_time), {ngx.var.server_name})
  metric_requests_uri:inc(1, {ngx.var.server_name,ngx.var.document_uri, ngx.var.status, ngx.var.request_method})
‘;

上面的metric_requests_uri模块是官方例子中没有的,是我自己添加的,取的是uri的访问记录,nginx中document_uri是不包含参数的,具体的参数都可以自行修改。

2.新建metrics对外导出监控数据

新建虚拟主机,端口自定义,添加下面的模块

1
2
3
4
5
6
7
8

location /metrics {
    content_by_lua_block {
      metric_connections:set(ngx.var.connections_reading, {“reading”})
      metric_connections:set(ngx.var.connections_waiting, {“waiting”})
      metric_connections:set(ngx.var.connections_writing, {“writing”})
      prometheus:collect()
    }
}

保存,重载nginx配置,访问metrics目录,可以看到监控数据

Nginx添加Prometheus监控模块nginx-lua-prometheus

其他

gafana上用的图是 462,因为uri是自己加的,需要添加下面的查询语句

1

sum(irate(nginx_http_requests_total{role=~”$role”,host!=”127.0.0.1″}[30s]))

© 版权声明
THE END
喜欢就支持一下吧
点赞14赞赏 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容