Ruby 追蹤 SDK

使用 Instana 進行追蹤是自動的,但如果您想要對自訂程式碼、特定應用程式區域或部分內部元件有更多可見性,則可以使用 Instana 的「Ruby 追蹤 SDK」,如下所示。

Instana Ruby 追蹤 SDK

Instana Ruby gem 提供簡單的使用 API 來追蹤應用程式的任何任意部分。

若要檢測程式碼區段,只需使用下列指令即可完成:

begin
  ::Instana.tracer.log_entry(:mywork, { :helpful_kvs => @user.id })
  # The code to be instrumented
  @id = User.find_by_name('john.smith')
rescue => e
  ::Instana.tracer.log_error(e)
ensure
  ::Instana.tracer.log_exit(:mywork, { :found_id => @id })
end

或者,您可以使用 trace 區塊方法,自動擷取並記載任何引發的異常狀況:

::Instana.tracer.trace(:mywork, { :helpful_kvs => @user.id }) do
  # The code to be instrumented
  @id = User.find_by_name('john.smith')
 end

以上是簡單的範例,但顯示如何輕鬆地檢測任何您喜歡的任意程式碼片段。

非同步追蹤

您要追蹤的部分作業可能是非同步的,這表示它們可能會立即傳回,但仍會繼續在頻外運作。 如果要這麼做,您可以使用 log_async_* 相關的追蹤方法:

::Instana.tracer.log_entry(:prep_job, { :helpful_kvs => @job.name })

http_ops = {:get => "/", :post => "/post_data"}

cb_block = Proc.new do |response, payload|
  # The callback block that is invoked on HTTP response (payload == t_context)
  #
  # process response
  #
  ::Instana.tracer.log_async_exit(:http_op, :status => response.status, payload)
end

http_ops.each do |op|
  t_context = ::Instana.tracer.log_async_entry(:http_op)

  # Example op that returns immediately
  request_id = connection.async_request(op, cb_block, t_context)

  ::Instana.tracer.log_async_info({:request_id => request_id}, t_context)
end  

將環境定義提至新執行緒

追蹤是本端執行緒。 如果您大量產生新的執行緒,則必須將環境定義帶入該新執行緒,然後再挑選。

# Get the tracing context
t_context = ::Instana.tracer.context

# Spawn new thread
Thread.new do
  # Pickup context in this thread with `t_context`
  ::Instana.tracer.log_start_or_continue(:async_thread, { :async_start => 1 }, t_context)

  # Continue tracing work as usual
  begin
    ::Instana.tracer.log_entry(:mywork, { :helpful_kvs => @user.id })
    # The code to be instrumented
    @id = User.find_by_name('john.smith')
  rescue => e
    ::Instana.tracer.log_error(e)
  ensure
    ::Instana.tracer.log_exit(:mywork, { :found_id => @id })
  end
end

追蹤稍後排定的工作

排入佇列等待稍後執行的工作可以檢測如下:

::Instana.tracer.log_entry(:prep_job, { :job_name => @job.name })

# Get the current tracing context
t_context = ::Instana.tracer.context

# The Async proc (job) that will be executed out of band.
block = Proc.new do
  # This will pickup context and link the two traces (root + job)
  t_context = ::Instana.tracer.log_start_or_continue_trace(:my_async_op, { :helpful_kvs => true }, t_context)
  #
  # Some Asynchronous work to be done
  #
  ::Instana.tracer.log_info({:job_name => Job.get(id).name})
  # More Asynchronous work
  ::Instana.tracer.log_end(:my_async_op, { :job_success => true })
end

MyClass.run_in_5_minutes(block)

::Instana.tracer.log_exit(:prep_job, { :prep_successful => true })

新增自訂標籤至 Instana 提供的跨距

若要將自訂標籤新增至 Instana 提供的文字段,請使用 set_tag 方法,並將下列雜湊附加至作用中文字段。

active_span = ::Instana.tracer.current_span

unless active_span.custom?
  custom_tags = {
    key: 'value'
  }

  active.span.set_tag(:sdk, {custom: {tags: custom_tags}})
end

另請參閱