Skip to content

Commit 129769f

Browse files
committed
feat: expose TraceId and ParentID to other plugins
This commit adds two fields to `kong.ctx.shared` and `ngx.var`: - `datadog_sdk_trace_id`: TraceId of the current span. - `datadog_sdk_span_id`: SpanId of the current span. Those fields can be consumed by other Kong plugins or in the underlying NGINX configuration for log correlation.
1 parent 15d7bd3 commit 129769f

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

kong/plugins/ddtrace/handler.lua

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ local subsystem = ngx.config.subsystem
88
local fmt = string.format
99
local strsub = string.sub
1010
local regex = ngx.re
11+
local btohex = bit.tohex
1112

1213
local DatadogTraceHandler = {
1314
VERSION = "0.2.0",
@@ -82,11 +83,26 @@ local function tag_with_service_and_route(span)
8283
end
8384
end
8485

86+
local function expose_tracing_variables(span)
87+
-- Expose traceID and parentID for other plugin to consume and also set an NGINX variable
88+
-- that can be use for in `log_format` directive for correlation with logs.
89+
-- NOTE: kong.ctx has the same lifetime as the current request.
90+
local trace_id = btohex(span.trace_id.high or 0, 16) .. btohex(span.trace_id.low, 16)
91+
local span_id = btohex(span.span_id, 16)
92+
93+
kong.ctx.shared.datadog_sdk_trace_id = trace_id
94+
kong.ctx.shared.datadog_sdk_span_id = span_id
95+
ngx.var.datadog_sdk_trace_id = trace_id
96+
ngx.var.datadog_sdk_span_id = span_id
97+
end
98+
8599
-- adds the proxy span to the datadog context, unless it already exists
86100
local function get_or_add_proxy_span(datadog, timestamp)
87101
if not datadog.proxy_span then
88102
local request_span = datadog.request_span
89-
datadog.proxy_span = request_span:new_child("kong.proxy", request_span.resource, timestamp)
103+
local proxy_span = request_span:new_child("kong.proxy", request_span.resource, timestamp)
104+
datadog.proxy_span = proxy_span
105+
expose_tracing_variables(proxy_span)
90106
end
91107
return datadog.proxy_span
92108
end
@@ -291,6 +307,8 @@ if subsystem == "http" then
291307
end
292308
end
293309

310+
expose_tracing_variables(request_span)
311+
294312
ctx.datadog = {
295313
request_span = request_span,
296314
proxy_span = nil,

0 commit comments

Comments
 (0)