15

我正在尝试在我的 Rails 日志中获取更多信息,特别是请求的 URI 或当前参数(如果可用)(我很感激它们不会总是如此)。但是我似乎无法做到。这是我到目前为止所做的:

#config/environments/production.rb
config.logger = Logger.new(config.log_path)
config.log_level = :error
config.logger.level = Logger::ERROR

#config/environment.rb
class Logger
  def format_message(level, time, progname, msg)
    "**********************************************************************\n#{level} #{time.to_s(:db)} -- #{msg}\n"
  end  
end

所以我可以很好地自定义消息,但我似乎无法在这里访问参数/请求变量。有谁知道这是否可行,如果可以,怎么办?或者是否有更好的方法来获取这些信息?(甚至可能是基于 Redis 的东西?)

感谢负载,

4

3 回答 3

29

(在被问到这个问题后很长时间才回复,但也许它会帮助下一个人。)

我只是做了类似的事情。

1)您需要与记录请求级别的详细信息分开覆盖您的记录器。看起来你已经想出定制你的记录器了。答案在这里: Rails logger 格式字符串配置

2)我将所有请求的请求和响应记录到我的服务中。请注意,Rails 将大量内容放入标头中,因此直接转储请求或标头可能不是一个好主意。另外值得注意的是,我的应用程序主要是通过 API 访问的。如果你的主要是一个网络应用程序,我猜大多数人都是,你可能不想检查 response.body ,因为它会包含你的 html。

class ApplicationController < ActionController::Base 
  around_filter :global_request_logging
...
  def global_request_logging 
    http_request_header_keys = request.headers.keys.select{|header_name| header_name.match("^HTTP.*")}
    http_request_headers = request.headers.select{|header_name, header_value| http_request_header_keys.index(header_name)}
    logger.info "Received #{request.method.inspect} to #{request.url.inspect} from #{request.remote_ip.inspect}.  Processing with headers #{http_request_headers.inspect} and params #{params.inspect}"
    begin 
      yield 
    ensure 
      logger.info "Responding with #{response.status.inspect} => #{response.body.inspect}"
    end 
  end 
end
于 2011-03-05T22:40:54.357 回答
3

这应该工作!:) 干杯。

logger.info({:user_agent => request.user_agent, :remote_ip => request.remote_ip}.inspect)

logger.info(params.inspect)

By by.. 这应该放在你的控制器动作中。例如:如果您将它放在创建操作中,它还应该记录 user_agent 即浏览器、remote_ip 即用户的远程 ip 和所有参数。

于 2010-04-19T15:38:00.793 回答
0

您应该查看请求类

喜欢提出 request.uri。

在此处查看更多详细信息http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html

于 2010-04-19T13:50:46.203 回答