TLDR:
A cleaner approach is add the following line to your environment.rb
file before the call to YourApp::Application.initialize!
:
NewRelic::Control.instance.env = 'em-process' if ($0 =~ /em-process/)
Details:
The trick is to ensure that NewRelic::Control.instance.env
is set before the newrelic_rpm.start_plugin
Railtie initializer runs (which starts the agent and reads that env
value). The reason this can't go in an initializer file is that files in config/initializers
get loaded after all Railtie initializers run.
With this approach you don't need to disable the auto-require on the newrelic_rpm gem in your Gemfile nor do you need to create a new initializer file, so it's a little cleaner.
Also in our case this approach was better because we don't want the New Relic agent running in rails consoles or migrations, so we have agent_enabled: false
in our newrelic.yml
file and we explicitly set the environment variable NEWRELIC_ENABLE=true
when we want to enable the agent (only when our processes run on Heroku). When we went with the config/initializers/new_relic.rb
approach it caused the agent to start up in rails consoles and migrations locally and on Heroku, which we didn't want. We tried to change the manual_start
call to:
NewRelic::Agent.manual_start(args) if ENV['NEWRELIC_ENABLE']
But then we got exceptions like undefined method 'add_method_tracer'
when NEWRELIC_ENABLE
wasn't set, because it's the call to NewRelic::Agent.manual_start
that makes those instrumentation methods available.
The upshot is that the newrelic_rpm gem wasn't designed to behave well when setting require: false
in the Gemfile
.