所以我有一个web服务,我需要将对该服务的URL请求记录到一个文件中。应该将其格式化为资源,例如:
/photo/23 firefox
/photo/23 chrome
/photo/24 chrome
/user/1 ie9
/user/2 ie9
/photo/67 chrome我的web服务是用Rails编写的,所以我想知道如何实现这种行为。使用什么宝石,在哪里放置记录器逻辑等。
发布于 2015-11-15 02:08:46
你不需要宝石。您可以将before_action钩子添加到application_controller.rb中:
class ApplicationController < ActionController::Base
before_action :log_actions
def log_actions
logger.debug "#{request.path} #{request.user_agent}"
end
end注1:如果您正在开发中,logger.debug将默认情况下在log/development.log文件中进行日志记录。如果您愿意,可以在任何其他文件中写入。
注2:request.path只为您提供资源路径(例如。/photo/23)。如果您还想在request.fullpath中包含GET参数(例如。/photo/23?page=1)
注3:request.user_agent给出了用户代理的完整描述,它很长:
eg. Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86您可以使用regex缩短它,如下所述:
示例:
def shortbrowser(mybrowser)
case mybrowser
when /MSIE/ then "Internet Explorer"
when /Chrome/ then "Chrome"
...
else mybrowser
end
end 然后使用它:
logger.debug "#{request.path} #{shortbrowser(request.user_agent)}"https://stackoverflow.com/questions/33715055
复制相似问题