In the handler.lua file, add an access function that increments the gauge as a request comes in, and a log function that increments the counter and decrements the gauge once the request finishes:
function MyPluginHandler:access(conf)
in_flight:add(1)
end
function MyPluginHandler:log(conf)
request_count:add(1, {
status = kong.response.get_status(),
method = kong.request.get_method(),
})
in_flight:add(-1)
end
Warning: The Metrics PDK doesn’t mask or redact attribute values. You’re responsible for what your plugin puts into an attributes table: don’t record sensitive data, like personally identifiable information, credentials, or tokens, as an attribute value.
The full handler.lua file now looks like this:
local http = require("resty.http")
local cjson = require("cjson.safe")
local MyPluginHandler = {
PRIORITY = 1000,
VERSION = "0.0.1",
}
local request_count = kong.metrics.counter("my_plugin.request.count", {
description = "Number of requests processed by my-plugin",
unit = "{request}",
})
local in_flight = kong.metrics.gauge("my_plugin.requests.in_flight", {
description = "Number of requests currently being processed by my-plugin",
unit = "{request}",
})
function MyPluginHandler:response(conf)
kong.log("response handler")
local httpc = http.new()
local res, err = httpc:request_uri("http://httpbin.konghq.com/anything", {
method = "GET",
})
if err then
return kong.response.error(500,
"Error when trying to access third-party service: " .. err,
{ ["Content-Type"] = "text/html" })
end
local body_table, err = cjson.decode(res.body)
if err then
return kong.response.error(500,
"Error when decoding third-party service response: " .. err,
{ ["Content-Type"] = "text/html" })
end
kong.response.set_header(conf.response_header_name, body_table.url)
end
function MyPluginHandler:access(conf)
in_flight:add(1)
end
function MyPluginHandler:log(conf)
request_count:add(1, {
status = kong.response.get_status(),
method = kong.request.get_method(),
})
in_flight:add(-1)
end
return MyPluginHandler
request_count only ever gets :add(1), because a counter must not decrease. in_flight uses :add(1) and :add(-1), because a gauge accepts negative deltas.