Skip to Content Skip to Search

Active Support Structured Event Subscriber

ActiveSupport::StructuredEventSubscriber consumes ActiveSupport::Notifications in order to emit structured events via Rails.event.

An example would be the Action Controller structured event subscriber, responsible for emitting request processing events:

module ActionController
  class StructuredEventSubscriber < ActiveSupport::StructuredEventSubscriber
    attach_to :action_controller

    def start_processing(event)
      emit_event("controller.request_started",
        controller: event.payload[:controller],
        action: event.payload[:action],
        format: event.payload[:format]
      )
    end
  end
end

After configured, whenever a "start_processing.action_controller" notification is published, it will properly dispatch the event (ActiveSupport::Notifications::Event) to the start_processing method. The subscriber can then emit a structured event via the emit_event method.

Methods
C
E
N
S

Constants

DEBUG_CHECK = proc { !ActiveSupport.event_reporter.debug_mode? }
 

Class Public methods

new()

# File activesupport/lib/active_support/structured_event_subscriber.rb, line 56
def initialize
  super
  @silenced_events = {}
end

Instance Public methods

call(event)

# File activesupport/lib/active_support/structured_event_subscriber.rb, line 88
def call(event)
  super
rescue => e
  handle_event_error(event.name, e)
end

emit_debug_event(name, payload = nil, caller_depth: 1, **kwargs)

Like emit_event, but only emits when the event reporter is in debug mode

# File activesupport/lib/active_support/structured_event_subscriber.rb, line 82
def emit_debug_event(name, payload = nil, caller_depth: 1, **kwargs)
  ActiveSupport.event_reporter.debug(name, payload, caller_depth: caller_depth + 1, **kwargs)
rescue => e
  handle_event_error(name, e)
end

emit_event(name, payload = nil, caller_depth: 1, **kwargs)

Emit a structured event via Rails.event.notify.

Arguments

  • name - The event name as a string or symbol

  • payload - The event payload as a hash or object

  • caller_depth - Stack depth for source location (default: 1)

  • kwargs - Additional payload data merged with the payload hash

# File activesupport/lib/active_support/structured_event_subscriber.rb, line 75
def emit_event(name, payload = nil, caller_depth: 1, **kwargs)
  ActiveSupport.event_reporter.notify(name, payload, caller_depth: caller_depth + 1, **kwargs)
rescue => e
  handle_event_error(name, e)
end

silenced?(event)

# File activesupport/lib/active_support/structured_event_subscriber.rb, line 61
def silenced?(event)
  ActiveSupport.event_reporter.subscribers.none? || @silenced_events[event]&.call
end