Skip to content

Instantly share code, notes, and snippets.

@lcrilly
Last active October 21, 2021 12:19
Show Gist options
  • Save lcrilly/840eb207d864cf1334733b47a05b363c to your computer and use it in GitHub Desktop.
Save lcrilly/840eb207d864cf1334733b47a05b363c to your computer and use it in GitHub Desktop.
Prometheus metrics for NGINX OSS using stub_status and js_body_filter

Prometheus metrics for NGINX open source

Converts the output of the NGINX stub_status module to Prometheus format so that basic metrics can be scraped from a /metrics endpoint.

The NGINX JavaScript module is used to filter the stub_status response.

$ curl -i http://localhost:8080/metrics
HTTP/1.1 200 OK
Server: nginx/1.21.3
Date: Thu, 21 Oct 2021 10:41:50 GMT
Content-Type: text/plain
Transfer-Encoding: chunked
Connection: keep-alive

connections{active} 1
connections{reading} 0
connections{writing} 1
connections{waiting} 0
server{accepts} 29
server{handled} 29
server{requests} 29
var connection_vars = ['active', 'reading', 'writing', 'waiting'];
var server_vars = ['accepts', 'handled', 'requests'];
var res = '';
function metrics(r, data, flags) {
res += data; // Collect the entire response,
if (flags.last) { // until we get the last byte.
var metrics = [];
connection_vars.forEach(m => metrics.push(`connections{${m}} ${r.variables['connections_' + m]}`));
var server_vals = res.split('\n')[2].trim().split(' ');
for (var i = 0; i < server_vars.length; i++) {
metrics.push(`server{${server_vars[i]}} ${server_vals[i]}`);
}
r.sendBuffer(metrics.join('\n') + '\n', flags);
}
}
function nolength(r) {
delete r.headersOut['Content-Length'];
}
export default { metrics, nolength }
js_import conf.d/prometheus.js;
server {
listen 8080;
location = /metrics {
stub_status;
js_header_filter prometheus.nolength;
js_body_filter prometheus.metrics;
}
location = /status {
stub_status;
}
location / {
default_type application/json;
return 200 '["/metrics", "/status"]\n';
}
}
# vim: syntax=nginx
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment