knyar / nginx-lua-prometheus

Prometheus metric library for Nginx written in Lua
MIT License
1.46k stars 231 forks source link

attempt to index global 'metric_requests' (a nil value) #132

Closed RorFis closed 2 years ago

RorFis commented 2 years ago

nginx.conf :

...
        lua_shared_dict prometheus_metrics 10M;
        lua_package_path "/home/myuser/nginx-lua-prometheus-master/?.lua";
    init_worker_by_lua_block {
      prometheus = require("prometheus").init("prometheus_metrics")
      metric_requests = prometheus:counter(
        "nginx_http_requests_total", "Number of HTTP requests", {"host", "status", "cache_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"})
    }
    log_by_lua_block {
      metric_requests:inc(1, {ngx.var.server_name, ngx.var.status, ngx.var.cache_status })
      metric_latency:observe(tonumber(ngx.var.request_time), {ngx.var.server_name})
    }
...

/etc/nginx/sites-enabled/metrics :

server {
  listen 9145;
  allow 127.0.0.1;
  deny all;
  error_log /var/log/nginx/metrics-error.log debug;
  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()
    }
  }
}

error.log :

...
2022/01/14 18:02:46 [error] 10538#10538: *6 lua entry thread aborted: runtime error: content_by_lua(metrics:12):2: attempt to index global 'metric_connections' (a nil value)
stack traceback:
coroutine 0:
        content_by_lua(metrics:12): in function <content_by_lua(metrics:12):1>, client: 127.0.0.1, server: , request: "GET /metrics HTTP/1.1", host: "localhost:9145"

...

2022/01/14 17:34:23 [error] 10538#10538: *5 failed to run log_by_lua*: log_by_lua(nginx.conf:79):2: attempt to index global 'metric_requests' (a nil value)
stack traceback:
        log_by_lua(nginx.conf:79):2: in function <log_by_lua(nginx.conf:79):1> while logging request, client: 127.0.0.1, server: , request: "GET /metrics HTTP/1.1", host: "localhost:9145"
...

Nginx -v : nginx version: nginx/1.10.3

curl http://localhost:9145/metrics :

<html>
<head><title>500 Internal Server Error</title></head>
<body bgcolor="white">
<center><h1>500 Internal Server Error</h1></center>
<hr><center>nginx/1.10.3</center>
</body>
</html>

I can't get the metrics from Nginx.

knyar commented 2 years ago

This is usually a symptom of lua module not being installed or enabled, or being out of date. The troubleshooting section of the README goes into a bit more detail. Good luck!