Add OTEL trace & span IDs to logs (#33339)

This commit is contained in:
Renaud Chaput 2024-12-18 08:34:20 +01:00 committed by GitHub
parent 3f9ac22af3
commit 3febe7d020
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -76,6 +76,34 @@ if ENV.keys.any? { |name| name.match?(/OTEL_.*_ENDPOINT/) }
)
end
end
# This middleware adds the trace_id and span_id to the Rails logging tags for every requests
class TelemetryLoggingMiddleware
def initialize(app)
@app = app
end
def call(env)
span = OpenTelemetry::Trace.current_span
unless span.recording?
@app.call(env)
return
end
span_id = span.context.hex_span_id
trace_id = span.context.hex_trace_id
Rails.logger.tagged("trace_id=#{trace_id}", "span_id=#{span_id}") do
@app.call(env)
end
end
end
Rails.application.configure do
config.middleware.insert_before Rails::Rack::Logger, TelemetryLoggingMiddleware
end
end
MastodonOTELTracer = OpenTelemetry.tracer_provider.tracer('mastodon')