Your data. Anywhere you go.

New Relic for iOS or Android

Download on the App Store    Android App on Google play

New Relic Insights App for iOS

Download on the App Store

Learn more

Close icon

Ruby Agent -- Record custom attribute for all Rails controllers



I’d like to add a unique transaction id generated within Rails to my application traces. It corresponds to other data we’re logging outside of New Relic.

I tried doing this in my ApplicationController with add_custom_attributes and add_transaction_tracer on a method that’s called by all requests (all_requests_method).

Unfortunately, this makes my transactions have names like RealController::all_requests_method instead of RealController::real_method.

What is the best way to add this unique transaction id? Would overriding the bad naming with set_transaction_name have any consequences for how the data is collected?

The only change I could see is that all transactions will now display Rack middleware data timing information which is annoying but could work.

Edit: My mistake, I put this in the wrong category


@max.short Thanks for your post. You should only need add_custom_attributes in order to add the custom attribute. If your goal is only to add the transaction id to each monitored transaction, you should be able to do this in ApplicationController without using add_transaction_tracer. add_transaciton_tracer is used to create top level transactions. This API call shouldn’t be necessary to add the attribute.

Here’s a code example outlining an approach you might want to take:

# application_controller.rb
class ApplicationController < ActionController::Base 
  before_filter :your_method

  def your_method
    NewRelic::Agent.add_custom_attributes({transaction_id: })

Let us know if you have any questions.


Thanks for your help Hakimu.

In case others encounter this problem here’s what I tried before and what ultimately ended up working:

What did not work

I tried setting NewRelic::Agent.add_custom_attributes in a method on another thread. I’m not sure if the other thread was the issue or if there was another problem.

I found a post on another forum that suggested starting the trace earlier. Thanks to Hakimu I know this is not necessary.

What worked

Due to the nature of our situation I ended up using an after_action. I used action instead of filter because of rails 5 deprecation.