From 8cdc616e486c6b24263fbeeb5515abc1fbe104cc Mon Sep 17 00:00:00 2001 From: bwang Date: Tue, 15 Sep 2026 14:37:34 +0800 Subject: [PATCH] fix: keep the error counter when a worker initializes again init() runs in every init_worker, including a respawned worker's, so setting the error counter to 0 wiped errors already counted by the other workers. Only create it when it does not exist. --- prometheus.lua | 3 ++- prometheus_test.lua | 5 +++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/prometheus.lua b/prometheus.lua index 8556b8d..8af6726 100644 --- a/prometheus.lua +++ b/prometheus.lua @@ -760,7 +760,8 @@ function Prometheus.init(dict_name, options_or_prefix) self.initialized = true self:counter(self.error_metric_name, "Number of nginx-lua-prometheus errors") - self.dict:set(self.error_metric_name, 0) + -- init runs in every init_worker, including a respawned worker's + self.dict:add(self.error_metric_name, 0) local err = self.key_index:add(self.error_metric_name, ERR_MSG_LRU_EVICTION) if err then self:log_error(err) diff --git a/prometheus_test.lua b/prometheus_test.lua index b485b0a..47b02a7 100644 --- a/prometheus_test.lua +++ b/prometheus_test.lua @@ -180,6 +180,11 @@ function TestPrometheus:testInit() luaunit.assertEquals(self.dict:get("nginx_metric_errors_total"), 0) luaunit.assertEquals(ngx.logs, nil) end +function TestPrometheus:testInitKeepsErrorCount() + self.dict:set("nginx_metric_errors_total", 3) + require('prometheus').init('metrics') + luaunit.assertEquals(self.dict:get("nginx_metric_errors_total"), 3) +end function TestPrometheus:testInitOptions() self.dict = setmetatable({}, SimpleDict) ngx.shared.metrics = self.dict