Can the Rails logger be accessed from within a Rack middleware?

白昼怎懂夜的黑 提交于 2019-12-23 10:02:54

问题


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. the logger is directly accessible in the rack environment
  2. the loger can be accessed at app boot time and assigned to the middleware

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.


回答1:


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

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.

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


来源:https://stackoverflow.com/questions/17331549/can-the-rails-logger-be-accessed-from-within-a-rack-middleware

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!