Module: Datadog::Contrib::Sinatra::Tracer

Defined in:
lib/ddtrace/contrib/sinatra/tracer.rb

Overview

Datadog::Contrib::Sinatra::Tracer is a Sinatra extension which traces requests.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.registered(app) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/ddtrace/contrib/sinatra/tracer.rb', line 34

def self.registered(app)
  ::Sinatra::Base.module_eval do
    def render(engine, data, *)
      output = ''
      tracer = Datadog.configuration[:sinatra][:tracer]
      if tracer.enabled
        tracer.trace(Ext::SPAN_RENDER_TEMPLATE, span_type: Datadog::Ext::HTTP::TEMPLATE) do |span|
          # If data is a string, it is a literal template and we don't
          # want to record it.
          span.set_tag(Ext::TAG_TEMPLATE_NAME, data) if data.is_a? Symbol

          output = super
        end
      else
        output = super
      end

      output
    end
  end

  app.use TracerMiddleware

  app.before do
    return unless Datadog.configuration[:sinatra][:tracer].enabled

    span = Sinatra::Env.datadog_span(env)
    span.set_tag(Datadog::Ext::HTTP::URL, request.path)
    span.set_tag(Datadog::Ext::HTTP::METHOD, request.request_method)
  end

  app.after do
    return unless Datadog.configuration[:sinatra][:tracer].enabled

    span = Sinatra::Env.datadog_span(env)

    unless span
      Datadog::Tracer.log.error('missing request span in :after hook')
      return
    end

    span.resource = "#{request.request_method} #{@datadog_route}"
    span.set_tag(Ext::TAG_ROUTE_PATH, @datadog_route)
    span.set_tag(Datadog::Ext::HTTP::STATUS_CODE, response.status)
    span.set_error(env['sinatra.error']) if response.server_error?
  end
end

Instance Method Details

#route(verb, action) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/ddtrace/contrib/sinatra/tracer.rb', line 18

def route(verb, action, *)
  # Keep track of the route name when the app is instantiated for an
  # incoming request.
  condition do
    # If the option to prepend script names is enabled, then
    # prepend the script name from the request onto the action.
    @datadog_route = if Datadog.configuration[:sinatra][:resource_script_names]
                       "#{request.script_name}#{action}"
                     else
                       action
                     end
  end

  super
end