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:
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With