class LittleGhost::Events::Reporter
Thread-safe event publisher with process-wide and fiber-scoped listeners. Reporters start without listeners so applications opt into their preferred event destination, including ConsoleListener for JSON-line diagnostics.
Public Class Methods
Source
# File lib/little_ghost/events.rb, line 58 def initialize(listeners: []) @mutex = Mutex.new @listeners = [] Array(listeners).each { |listener| subscribe(listener) } end
Starts with listeners in subscription order.
Public Instance Methods
Source
# File lib/little_ghost/events.rb, line 114 def context deep_copy(ExecutionState[context_key] || {}) end
Copies the event context active in the current execution.
# File lib/little_ghost/events.rb, line 83 def emit(level, name, payload = {}) level = level.to_sym raise ArgumentError, "unknown event level: #{level}" unless LEVELS.include?(level) raise ArgumentError, "event payload must be a hash" unless payload.is_a?(Hash) event = { name: normalize_string(name.to_s), level:, payload: deep_copy(payload), context: context, timestamp: Process.clock_gettime(Process::CLOCK_REALTIME, :nanosecond) } listeners.each do |entry| listener = entry.fetch(:listener) filter = entry[:filter] next if filter && !filter.call(deep_copy(event)) listener.emit(deep_copy(event)) rescue nil end event end
Delivers an event and returns a detached copy of its complete hash.
# File lib/little_ghost/events.rb, line 65 def subscribe(listener, &filter) unless listener.respond_to?(:emit) raise ArgumentError, "event listener must respond to emit" end @mutex.synchronize { @listeners << {listener:, filter:} } listener end
Subscribes listener. The optional block filters copied event hashes.
Source
# File lib/little_ghost/events.rb, line 75 def unsubscribe(listener) @mutex.synchronize do @listeners.delete_if { |entry| listener === entry.fetch(:listener) } end listener end
Unsubscribes every entry matching listener.
# File lib/little_ghost/events.rb, line 108 def with_context(attributes) values = context.merge(deep_copy(attributes.compact)) ExecutionState.with(context_key => values) { yield } end
Adds attributes to events emitted while the block runs.