Search code examples
ruby-on-railsmiddlewarenewrelic

New Relic log http_referer on every request


We have this beofre_filter in application controller in order to log the HTTP_REFER in first place

  def init_newrelic_agent
      ::NewRelic::Agent.add_custom_parameters(
        request_referer: request.referer,
        request_url: request.url,
        request_user_agent: request.user_agent
      )
    end

This adds the above custom parameters only if the request lands in the rails controller. However some requests don't even land there, because they hit our app with the false route for example. How would you configure rails to log this params in newrelic on every application trace even if some errors occur before even the controller is initialized?


Solution

  • For those who interested, below the concrete implementation:

    #config/initializers/newrelic.rb
    Rails.configuration.middleware.use  NewRelic::Rack::Custom  
    
    #app/middlewares/newrelic/rack/custom.rb
    module NewRelic
      module Rack
    
        class Custom
          def initialize(app)
            @app = app
          end
    
          def call(env)
            init_newrelic_agent(env)
            @app.call(env)
          end
    
          def init_newrelic_agent(env)
            ::NewRelic::Agent.add_custom_parameters(
              request_referer: env['HTTP_REFERER'],
              request_url: env['REQUEST_URI'],
              request_user_agent: env['HTTP_USER_AGENT']
            )
          end
    
        end
      end
    end