Skip to content

Instantly share code, notes, and snippets.

@WoozyMasta
Created May 25, 2023 08:37
Show Gist options
  • Save WoozyMasta/d7f333847104cd31aa51bff89bdf6210 to your computer and use it in GitHub Desktop.
Save WoozyMasta/d7f333847104cd31aa51bff89bdf6210 to your computer and use it in GitHub Desktop.
Openresty prometheus metrics
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"}
)
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_client_ips = prometheus:counter(
"client_ips",
"Number of requests by client IP",
{"host", "ip"}
)
metric_user_agent = prometheus:counter(
"nginx_http_user_agent_counts",
"Number of requests by User-Agent",
{"user_agent"}
)
metric_referer = prometheus:counter(
"nginx_http_referer_ips",
"Number of requests by Referer IP",
{"ip"}
)
}
log_by_lua_block {
metric_requests:inc(1, {ngx.var.server_name, ngx.var.status})
metric_latency:observe(tonumber(ngx.var.request_time), {ngx.var.server_name})
metric_client_ips:observe(1, {ngx.var.server_name, ngx.var.remote_addr})
local user_agent = ngx.var.http_user_agent
if user_agent then
metric_user_agent:inc(1, {user_agent})
end
local referer = ngx.var.http_referer
if referer then
local http = require("resty.http")
local httpc = http.new()
local parsed_url = httpc:parse_uri(referer)
metric_referer:inc(1, {parsed_url.host})
end
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment