Reputation: 1364
So I have a web service and I need to log URL requests to that service to a file. It should be formatted as [resource] [browser], for example like this:
/photo/23 firefox
/photo/23 chrome
/photo/24 chrome
/user/1 ie9
/user/2 ie9
/photo/67 chrome
My web service is written in Ruby on Rails, so I am wondering how to achieve this behaviour. What gem to use, where to put logger logic etc.
Upvotes: 0
Views: 291
Reputation: 76
You don't need a gem. You can add before_action hook in your application_controller.rb :
class ApplicationController < ActionController::Base
before_action :log_actions
def log_actions
logger.debug "#{request.path} #{request.user_agent}"
end
end
NOTE 1: logger.debug
will log by default in the log/development.log
file if you are in development. You can write in any other file if you like.
NOTE 2: request.path
gives you the resource path alone (eg. /photo/23
). If you also want to include the GET parameters with request.fullpath
(eg. /photo/23?page=1
)
NOTE 3: request.user_agent
gives a full description of the user agent which is long:
eg. Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86
You can make it shorter with regex as described here:
example:
def shortbrowser(mybrowser)
case mybrowser
when /MSIE/ then "Internet Explorer"
when /Chrome/ then "Chrome"
...
else mybrowser
end
end
Then use it:
logger.debug "#{request.path} #{shortbrowser(request.user_agent)}"
Upvotes: 1