可以从Rack中间件中访问Rails记录器吗? [英] Can the Rails logger be accessed from within a Rack middleware?

查看:68
本文介绍了可以从Rack中间件中访问Rails记录器吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用该应用程序的现有记录器从要放入Rails应用程序的中间件中记录内容.有没有标准的方法可以做到这一点?我想到了两种可能性:

I'd like to log things from within a middleware that I'm putting into a Rails app, using the app's existing logger. Is there a standard way to do this? Two possibilities that come to mind:

  1. 可以在机架环境中直接访问记录器
  2. 可以在应用启动时访问记录器并将其分配给中间件

搜索涉及这两个方面的解决方案的建议并不多.我还没有完全考虑/实验一下操作顺序是否允许.

Searching for solutions involving either of these doesn't come up with much. I haven't fully thought through/experimented to see if the order of operations allows either to be possible.

推荐答案

我已经能够通过编写自己的中间件(仅将Rails.logger添加到Rack环境中)来使其工作.

I've been able to get this to work by writing my own middleware which just adds the Rails.logger to the Rack environment.

module Something
  class UseRailsLogger
    def initialize(app)
      @app = app
    end
    def call(env)
      env['rack.logger'] ||= Rails.logger
      @app.call(env)
    end
  end
end

如果将其存储在lib/something/use_rails_logger.rb中,则可以将其添加到中间件堆栈中,记录器将可用于其后的每一层.

If you stash that in lib/something/use_rails_logger.rb, then you can add it to your middleware stack and the logger will be available to every layer that comes after it.

注意:我想将其添加到config/application.rb,因为没有理由将此设置依赖于环境,但是出于某些原因,require 'something/use_rails_logger'在该文件中不起作用.将其添加到config/environment/*.rb效果很好.在require旁边,您只需:

Note: I wanted to add it to config/application.rb since there's no reason for this setting to be environment-dependent, but for some reason require 'something/use_rails_logger' wouldn't work from that file. Adding it to config/environment/*.rb worked just fine. Beside the require all you need is:

config.middleware.use Rack::UseRailsLogger

这篇关于可以从Rack中间件中访问Rails记录器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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