Class: OpenCensus::Trace::Integrations::Rails

Inherits:
Rails::Railtie
  • Object
show all
Defined in:
lib/opencensus/trace/integrations/rails.rb

Overview

# Rails Integration

This Railtie automatically sets up OpenCensus for a Rails server:

  • It wraps all requests in spans, using the ‘RackMiddleware` integration.

  • It wraps common events (ActiveRecord database calls, ActionView renders, etc) in subspans.

## Configuration

This Railtie exposes the OpenCensus configuration on the ‘opencensus` key of the Rails configuration. So you can, for example, set:

config.opencensus.trace.default_max_attributes = 64

This Railtie also provides a ‘notifications` configuration that supports the following fields:

  • ‘events` An array of strings indicating the events that will trigger the creation of spans. The default value is DEFAULT_NOTIFICATION_EVENTS.

  • ‘attribute_namespace` A string that will be prepended to all attributes copied from the event payload. Defaults to “`rails/`”

You can access these in the ‘notifications` subconfiguration under the trace configuration. For example:

OpenCensus::Trace.config do |config|
  config.notifications.attribute_namespace = "myapp/"
end

Or, using Rails:

config.opencensus.trace.notifications.attribute_namespace = "myapp/"

Constant Summary collapse

DEFAULT_NOTIFICATION_EVENTS =

The ActiveSupport notifications that will be reported as spans by default. To change this list, update the value of the ‘trace.notifications.events` configuration.

[
  "sql.active_record",
  "render_template.action_view",
  "send_file.action_controller",
  "send_data.action_controller",
  "deliver.action_mailer"
].freeze

Instance Method Summary collapse

Instance Method Details

#handle_notification_event(event) ⇒ Object

Add a span based on a notification event.



106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/opencensus/trace/integrations/rails.rb', line 106

def handle_notification_event event
  span_context = OpenCensus::Trace.span_context
  if span_context
    ns = OpenCensus::Trace.configure.notifications.attribute_namespace
    span = span_context.start_span event.name, skip_frames: 2
    span.start_time = event.time
    span.end_time = event.end
    event.payload.each do |k, v|
      span.put_attribute "#{ns}#{k}", v.to_s
    end
  end
end

#setup_notificationsObject

Initialize notifications



93
94
95
96
97
98
99
100
# File 'lib/opencensus/trace/integrations/rails.rb', line 93

def setup_notifications
  OpenCensus::Trace.configure.notifications.events.each do |type|
    ActiveSupport::Notifications.subscribe(type) do |*args|
      event = ActiveSupport::Notifications::Event.new(*args)
      handle_notification_event event
    end
  end
end