在Rails记录器中包括参数/请求信息吗? [英] Include params/request information in Rails logger?

查看:70
本文介绍了在Rails记录器中包括参数/请求信息吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Rails日志中获取更多信息,尤其是请求的URI或当前参数(如果可用)(并且我知道它们不会一直存在).但是我似乎没能力.到目前为止,这是我所做的:

I'm trying to get some more information into my Rails logs, specifically the requested URI or current params, if available (and I appreciate that they won't always be). However I just don't seem able to. Here's what I've done so far:

#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

所以我可以自定义消息,但是我似乎无法在此处访问params/request变量.有谁知道这是否可能,如果可以,怎么办?或者,如果有更好的方法来获取此信息? (也许甚至是基于Redis的东西?)

So I can customize the message fine, yet I don't seem to be able to access the params/request variables here. Does anyone know if this is possible, and if so how? Or if there's a better way to get this information? (Perhaps even something Redis based?)

感谢负载,

推荐答案

(被问及回答很长时间之后,但这也许会对下一个人有所帮助.)

(Responding a long time after this was asked, but maybe it will help the next person.)

我刚刚做了类似的事情.

I just did something similar.

1)您需要与记录请求级详细信息分开覆盖记录器.看起来您已经确定要定制记录器了.答案在这里: 轨道记录器格式字符串配置

1) you need to override your logger separately from logging request-leve details. Looks like you've figured customizing your logger out. Answer is here: Rails logger format string configuration

2)我将请求和所有请求的响应记录到我的服务中.注意,Rails在标题中放入了很多东西,因此直接转储请求或标题可能是个坏主意.还要注意的是,我的应用程序主要是通过API访问的.如果您主要是一个网络应用程序(正如我猜到的大多数人一样),则您可能不想检查response.body,因为它将包含您的html.

2) I log the request and response of all requests into my service. Note, that Rails puts a tonne of stuff into the headers, so just straight dumping the request or the headers is probably a bad idea. Also of note, my application is primarily accessed via an API. If yours is primarily a web-app, as I'm guessing most people's are, you probably don't want to inspect the response.body as it will contain your 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

这篇关于在Rails记录器中包括参数/请求信息吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆