Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log use of the default route in rails

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.

like image 546
Blake Taylor Avatar asked Mar 08 '12 21:03

Blake Taylor


People also ask

How do I see routes in Rails?

TIP: If you ever want to list all the routes of your application you can use rails routes on your terminal and if you want to list routes of a specific resource, you can use rails routes | grep hotel . This will list all the routes of Hotel.

What is RESTful route in Rails?

In Rails, a RESTful route provides a mapping between HTTP verbs, controller actions, and (implicitly) CRUD operations in a database. A single entry in the routing file, such as. map.resources :photos. creates seven different routes in your application: HTTP verb.

Where does Rails logger info write to?

In a Rails app, logs are stored under the /log folder. In development mode, the development. log file is used & you see log output on the terminal you're running rails server on.

What does as do in Rails routes?

The :as option creates a named path. You can then call this path in your controllers and views (e.g. redirect_to things_path ). This isn't very useful for the root path (as it already named root ), but is very useful for new routes you add.


2 Answers

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.

like image 192
myabc Avatar answered Nov 08 '22 07:11

myabc


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
like image 24
Don Cruickshank Avatar answered Nov 08 '22 07:11

Don Cruickshank