nginx 流模块的指标

Metrics for nginx stream module

我正在尝试从 nginx 获取有关使用 nginx 流模块时总连接数的指标。我知道有 stub_status 选项,但它看起来只适用于 http 而不是流。

我找到了有流的 prometheus lua plugin,但我无法找到适合它的配置文件。我只得到 built-in 错误指标,但没有得到定义的指标。这是 conf 和响应。同样奇怪的是,响应是在 header 而不是 body.

stream {
   lua_shared_dict prometheus_metrics 10M;
   lua_package_path "/tmp/nginx-lua-prometheus/?.lua;/usr/local/openresty/luajit/lib/lua/5.1/?.lua;;";
   init_by_lua '
      prometheus = require("prometheus").init("prometheus_metrics")
      metric_requests = prometheus:counter("nginx_http_requests_total", "Number of HTTP requests", {"test"})
      metric_connections = prometheus:gauge("nginx_http_connections", "Number of HTTP connections", {"test"})';
   log_by_lua_block {
     metric_requests:inc(1, {"test"})
   }

server {
  listen 9145;
  content_by_lua '
    local sock = assert(ngx.req.socket(true))
    local data = sock:receive()
    local location = "GET /metrics"
    if string.sub(data, 1, string.len(location)) == location then
      ngx.say("HTTP/1.1 200 OK")
      ngx.say("Content-Type: text/plain")
      ngx.say("yo")
      ngx.say(table.concat(prometheus:metric_data(), ""))
    else
      ngx.say("HTTP/1.1 404 Not Found")
    end
  ';
  }
}

curl localhost:9145/metrics -v
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 9145 (#0)
> GET /metrics HTTP/1.1
> Host: localhost:9145
> User-Agent: curl/7.52.1
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: text/plain
< # HELP nginx_metric_errors_total Number of nginx-lua-prometheus errors
< # TYPE nginx_metric_errors_total counter
< nginx_metric_errors_total 0
* no chunk, no close, no size. Assume close to signal end
<
* Curl_http_done: called premature == 0
* Closing connection 0

https://github.com/knyar/nginx-lua-prometheus/issues/77

在这里回答

  log_by_lua_block {
    metric_connections:set(ngx.var.connections_active, {"active"})
    metric_connections:set(ngx.var.connections_reading, {"reading"})
    metric_connections:set(ngx.var.connections_writing, {"writing"})
    metric_connections:set(ngx.var.connections_waiting, {"waiting"})
    metric_requests:inc(1, {"test"})
  }