在 ActiveSupport::LogSubscriber 子类中访问 Rails 请求 [英] Access to Rails request inside ActiveSupport::LogSubscriber subclass

查看:68
本文介绍了在 ActiveSupport::LogSubscriber 子类中访问 Rails 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一些自定义 Rails 记录器,它最终将记录到数据库中.但是,我无法访问我非常希望拥有的请求对象之类的东西.

I am trying to make a bit of a custom Rails logger which ultimately will log to a database. However, I don't have access to things like the request object, which I very much would like to have.

我目前正在尝试使用 LogSubscriber(通知)接口来完成大部分工作;也许这不是正确的方法.我知道我可以滥用 Thread.current[] 但我希望避免这样做.

I'm currently trying to use the LogSubscriber (notification) interface to do the bulk of this; perhaps this is not the right approach. I do know I could abuse Thread.current[] but I was hoping to avoid doing that.

这是我拥有的代码,作为示例,它是我所能获得的最基本的代码.这是在初始化程序中加载的.

Here's the code I have which is as basic as I can get it for an example. This is loaded in an initializer.

module RequestLogging
  class LogSubscriber < ActiveSupport::LogSubscriber
    def process_action(event)
      pp request # <--- does not work
      pp event
    end
end

RequestLogging::LogSubscriber.attach_to :action_controller

推荐答案

可能你需要覆盖 ActionController::Instrumentation 中的 process_action ,然后请求对象就可以像 event.payload[:请求].我认为您可以将代码放在 config/initializers 中的某处,代码示例:

Probably you need to override process_action in ActionController::Instrumentation and then request object will be accessible like event.payload[:request]. I think you can put code somewhere in config/initializers, code example:

ActionController::Instrumentation.class_eval do
  def process_action(*args)
    raw_payload = {
      controller: self.class.name,
      action:     self.action_name,
      params:     request.filtered_parameters,
      format:     request.format.try(:ref),
      method:     request.method,
      path:       (request.fullpath rescue "unknown"),
      request:    request,
      session:    session
    }

    ActiveSupport::Notifications.instrument("start_processing.action_controller", raw_payload.dup)

    ActiveSupport::Notifications.instrument("process_action.action_controller", raw_payload) do |payload|
      result = super
      payload[:status] = response.status
      append_info_to_payload(payload)
      result
    end
  end
end

这篇关于在 ActiveSupport::LogSubscriber 子类中访问 Rails 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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