Class: OmniAI::Instrumentation

Inherits:
Object
  • Object
show all
Defined in:
lib/omniai/instrumentation.rb

Overview

Used for logging.

Instance Method Summary collapse

Constructor Details

#initialize(logger:) ⇒ Instrumentation

Returns a new instance of Instrumentation.

Parameters:

  • logger (Logger)


7
8
9
# File 'lib/omniai/instrumentation.rb', line 7

def initialize(logger:)
  @logger = logger
end

Instance Method Details

#finish(_, payload) ⇒ Object

Parameters:

  • payload (Hash)

Options Hash (payload):

  • :response (HTTP::Response)


58
59
60
# File 'lib/omniai/instrumentation.rb', line 58

def finish(_, payload)
  log_response(payload[:response])
end

#instrument(name, payload = {}) ⇒ Object

ActiveSupport::Notifications-compatible instrument.

On http 6 the instrumentation feature drives every request through ‘around_request`, which (per http’s own feature docs) “emits two events on every request: ‘start_request.http` before the request is made [and] `request.http` after the response is received”. Both are delivered here as `instrument(name) { … }` calls: the start event carries an empty block, and the request event’s block wraps the exchange and returns the response. The block of the request event MUST be yielded and its value returned, otherwise the response is lost as ‘nil` (http uses the return value as the response). We log the request on the start event and the response on the request event. The event namespace is caller-configurable (the names are `start_request.#namespace` / `request.#namespace`), so #start_event? prefix-matches rather than comparing the full name.

On http 5 this is only ever called without a block (for the start and error events); request/response logging there happens via #start / #finish.

Parameters:

  • name (String)
  • payload (Hash) (defaults to: {})

Options Hash (payload):

  • :request (HTTP::Request)
  • :response (HTTP::Response)
  • :error (Exception)


34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/omniai/instrumentation.rb', line 34

def instrument(name, payload = {})
  error = payload[:error]
  @logger.error("#{name}: #{error.message}") if error

  return unless block_given?

  if start_event?(name)
    log_request(payload[:request])
    yield payload
  else
    response = yield payload
    log_response(payload[:response] || response)
    response
  end
end

#start(_, payload) ⇒ Object

Parameters:

  • payload (Hash)

Options Hash (payload):

  • :request (HTTP::Request)


52
53
54
# File 'lib/omniai/instrumentation.rb', line 52

def start(_, payload)
  log_request(payload[:request])
end