ruby-on-railsrubynewrelicapm

How to obtain TraceId from a New Relic transaction?


I have a Rails app that's running new relic's ruby agent v7.2 and distributed tracing is enabled. Having distributed tracing enabled lets NR create a "TraceId" attribute for every api call thats getting logged and I can see that in my dashboard. But is there a way I can obtain that TraceId and pass it on as a response header to my clients that make the API call to my Rails app?

Gone about the https://github.com/newrelic/newrelic-ruby-agent documentation but haven't really found an answer yet.

To be clear what I'm trying to do is pass on the NR Trace ID as a header to the client in my application_controller.rb

after_action :set_trace_id_header
.
.
.
def set_trace_id_header
   response.headers["NR-TraceId"] = get_nr_trace_id
end

def get_nr_trace_id
  # NewRelic::Agent.something_to_get_traceid_from_current_transaction?
end

Solution

  • From any transaction you can run NewRelic::Agent::Tracer.current_trace_id to return the current trace_id:

    NewRelic::Agent::Tracer.current_trace_id
    => "7e33f5a5da3495380cb2408dc0d64053"
    

    This is found in lib/new_relic/agent/tracer.rb.

    Beware that even though you may find a trace_id for a given transaction that trace may not be sent to New Relic depending on a number of factors explained in Technical distributed tracing details. That means that you may be tracking locally trace_id values that are never sent to New Relic and thus not searchable in their tools.