nginx stream module的度量指标

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

我发现了prometheus lua插件,它有流,但是我无法找出正确的设置。我只得到了内置的错误指标,但没有定义的指标。这是conf和响应。另外奇怪的是响应在头部而不是正文中。

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", "HTTP请求数", {"test"})
      metric_connections = prometheus:gauge("nginx_http_connections", "HTTP连接数", {"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 nginx-lua-prometheus错误数
< # 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
点赞
用户3748325
用户3748325

在这里回答

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"})
}

在此代码块中,使用 Lua 在日志阶段为 Prometheus 指标设置值。其中 metric_connectionsmetric_requests 是预定义的 Prometheus counters,分别表示连接数和请求数。第一个 set函数将当前活动的连接数保存到 metric_connections 中,并与名为 active 的 label 关联。类似地,readingwritingwaiting 标签与相应的连接统计信息关联。最后一个 inc函数将一个值为 1 的计数器递增,并将名为 test 的 label 与其关联。

2020-07-05 21:30:10