Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 824
John Bachir Avatar asked Oct 22 '22 06:10

John Bachir


1 Answers

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
like image 95
benzado Avatar answered Oct 27 '22 09:10

benzado