问题
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:
- the logger is directly accessible in the rack environment
- 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