Log use of the default route in rails
Asked Answered
P

2

7

I am trying to remove the "catch all" or "default" route from a production rails application. I'm interested in maintaining operation while gathering a log of it's usage so that I can replace it with the appropriate hard coded routes.

So, given I have the following default route line in my config/routes.rb file.

match '/:controller(/:action(/:id))'

How could I create or retrieve a log of every time that route gets hit. This log would ideally include only requests actually handled by this route along with parameters and would need to leave the route itself functioning as normal.

Pedalfer answered 8/3, 2012 at 21:49 Comment(0)
S
7

One way you can do this is the change the default route to:

match ':controller(/:action(/:id))(.:format)', :using_default_route => true

Then put the following function into app/controllers/application_controller.rb

before_filter do
  if params[:using_default_route]
    logger.info("Default route for #{request.path.inspect}. params = #{params.inspect}")
  end
end
Salba answered 8/3, 2012 at 22:45 Comment(1)
Just an update. While this works for logging the incoming routes, it causes route generation for the default route to not match (as the using_default_route isn't passed). I've fixed this by adding a second match after the first that will allow the generation, and it existence would get picked up if it gets used. However, my fear is removing both of these lines eventually will cause those views to fail. It would be great if there was a way to log generation which uses the default route too.Pedalfer
L
8

Another possibility would be to make use of Rails router constraints option:

match '/:controller(/:action(/:id))', constraints: -> (req) {
  Rails.logger.info("Default route used: #{req.path.inspect}")
  true
}

Note: the lambda returns true so that the match succeeds.

Linotype answered 3/5, 2014 at 20:1 Comment(0)
S
7

One way you can do this is the change the default route to:

match ':controller(/:action(/:id))(.:format)', :using_default_route => true

Then put the following function into app/controllers/application_controller.rb

before_filter do
  if params[:using_default_route]
    logger.info("Default route for #{request.path.inspect}. params = #{params.inspect}")
  end
end
Salba answered 8/3, 2012 at 22:45 Comment(1)
Just an update. While this works for logging the incoming routes, it causes route generation for the default route to not match (as the using_default_route isn't passed). I've fixed this by adding a second match after the first that will allow the generation, and it existence would get picked up if it gets used. However, my fear is removing both of these lines eventually will cause those views to fail. It would be great if there was a way to log generation which uses the default route too.Pedalfer

© 2022 - 2024 — McMap. All rights reserved.