diff --git a/apisix/plugins/loki-logger.lua b/apisix/plugins/loki-logger.lua index 593fc8b18e6c..357ab1978202 100644 --- a/apisix/plugins/loki-logger.lua +++ b/apisix/plugins/loki-logger.lua @@ -192,18 +192,18 @@ function _M.log(conf, ctx) return end - -- generate a function to be executed by the batch processor - local func = function(entries) - local labels = conf.log_labels - - -- parsing possible variables in label value - for key, value in pairs(labels) do - local new_val, err, n_resolved = core.utils.resolve_var(value, ctx.var) - if not err and n_resolved > 0 then - labels[key] = new_val - end + local labels = conf.log_labels + + -- parsing possible variables in label value + for key, value in pairs(labels) do + local new_val, err, n_resolved = core.utils.resolve_var(value, ctx.var) + if not err and n_resolved > 0 then + labels[key] = new_val end + end + -- generate a function to be executed by the batch processor + local func = function(entries) -- build loki request data local data = { streams = { diff --git a/t/plugin/loki-logger.t b/t/plugin/loki-logger.t index faa8749a917d..72c79f1e97a6 100644 --- a/t/plugin/loki-logger.t +++ b/t/plugin/loki-logger.t @@ -306,3 +306,71 @@ hello world } } --- error_code: 200 + + + +=== TEST 12: setup route (with log_labels as variables) +--- config + location /t { + content_by_lua_block { + local t = require("lib.test_admin").test + local code, body = t('/apisix/admin/routes/1', + ngx.HTTP_PUT, + [[{ + "plugins": { + "loki-logger": { + "endpoint_addrs": ["http://127.0.0.1:3100"], + "tenant_id": "tenant_1", + "log_labels": { + "custom_label": "$remote_addr" + }, + "batch_max_size": 1 + } + }, + "upstream": { + "nodes": { + "127.0.0.1:1980": 1 + }, + "type": "roundrobin" + }, + "uri": "/hello" + }]] + ) + + if code >= 300 then + ngx.status = code + end + ngx.say(body) + } + } +--- response_body +passed + + + +=== TEST 13: hit route +--- request +GET /hello +--- response_body +hello world + + + +=== TEST 14: check loki log (with custom_label) +--- config + location /t { + content_by_lua_block { + local cjson = require("cjson") + local now = ngx.now() * 1000 + local data, err = require("lib.grafana_loki").fetch_logs_from_loki( + tostring(now - 3000) .. "000000", -- from + tostring(now) .. "000000", -- to + { query = [[{custom_label="127.0.0.1"} | json]] } + ) + + assert(err == nil, "fetch logs error: " .. (err or "")) + assert(data.status == "success", "loki response error: " .. cjson.encode(data)) + assert(#data.data.result > 0, "loki log empty: " .. cjson.encode(data)) + } + } +--- error_code: 200