Skip to content

Commit 8828772

Browse files
authored
fix: set span name to sinatra.route (#434)
The previous attempt at this failed due to sinatra.route not having been set yet. This moves the logic for using sinatra.route to later in the process and only updates the span name if sinatra.route exists.
1 parent bb1ad6b commit 8828772

File tree

2 files changed

+28
-6
lines changed

2 files changed

+28
-6
lines changed

instrumentation/sinatra/lib/opentelemetry/instrumentation/sinatra/middlewares/tracer_middleware.rb

+2-3
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,8 @@ def initialize(app)
1515
end
1616

1717
def call(env)
18-
span_name = env['sinatra.route'] || env['PATH_INFO']
19-
2018
tracer.in_span(
21-
span_name,
19+
env['PATH_INFO'],
2220
attributes: { 'http.method' => env['REQUEST_METHOD'],
2321
'http.url' => env['PATH_INFO'] },
2422
kind: :server,
@@ -46,6 +44,7 @@ def trace_response(span, env, resp)
4644
span.set_attribute('http.status_code', status)
4745
span.set_attribute('http.status_text', ::Rack::Utils::HTTP_STATUS_CODES[status])
4846
span.set_attribute('http.route', env['sinatra.route'].split.last) if env['sinatra.route']
47+
span.name = env['sinatra.route'] if env['sinatra.route']
4948
span.status = OpenTelemetry::Trace::Status.http_to_status(status)
5049
end
5150
end

instrumentation/sinatra/test/opentelemetry/instrumentation/sinatra_test.rb

+26-3
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,10 @@
2727
get '/with_template' do
2828
erb :foo_template
2929
end
30+
31+
get '/api/v1/foo/:myname/?' do
32+
'Some name'
33+
end
3034
end
3135
end
3236

@@ -96,14 +100,33 @@
96100

97101
_(exporter.finished_spans.size).must_equal 3
98102
_(exporter.finished_spans.map(&:name))
99-
.must_equal %w[sinatra.render_template
100-
sinatra.render_template
101-
/with_template]
103+
.must_equal [
104+
'sinatra.render_template',
105+
'sinatra.render_template',
106+
'GET /with_template'
107+
]
102108
_(exporter.finished_spans[0..1].map(&:attributes)
103109
.map { |h| h['sinatra.template_name'] })
104110
.must_equal %w[layout foo_template]
105111
end
106112

113+
it 'correctly name spans' do
114+
get '/one//api/v1/foo/janedoe/'
115+
116+
_(exporter.finished_spans.size).must_equal 1
117+
_(exporter.finished_spans.first.attributes).must_equal(
118+
'http.method' => 'GET',
119+
'http.url' => '/api/v1/foo/janedoe/',
120+
'http.status_code' => 200,
121+
'http.status_text' => 'OK',
122+
'http.route' => '/api/v1/foo/:myname/?'
123+
)
124+
_(exporter.finished_spans.map(&:name))
125+
.must_equal [
126+
'GET /api/v1/foo/:myname/?'
127+
]
128+
end
129+
107130
it 'does not create unhandled exceptions for missing routes' do
108131
get '/one/missing_example/not_present'
109132

0 commit comments

Comments
 (0)