Question

I'm using sinatra/assetpack and thin. How do I turn off logging the asset requests like quiet assets for Rails?

Was it helpful?

Solution

Got assets turned off with this:

module Sinatra
  module QuietLogger

    @extensions = %w(png gif jpg jpeg woff tff svg eot css js coffee scss)

    class << self
      attr_accessor :extensions

      def registered(app)
        ::Rack::CommonLogger.class_eval <<-PATCH
          alias call_and_log call

          def call(env)
            ext = env['REQUEST_PATH'].split('.').last
            if #{extensions.inspect}.include? ext
              @app.call(env)
            else
              call_and_log(env)
            end
          end
        PATCH
      end
    end

  end
end

And then simply register it in the app:

configure :development
  register QuietLogger
end

OTHER TIPS

Sinatra's logger is just a subclass of Rack::CommonLogger. More importantly, the logger portion is a middleware that gets attached to the Sinatra App. If your have your own implementation of logger based on the Rack::CommonLogger module (or your own middleware), that can be added to Sinatra like so:

use MyOwnLogger

We will subclass Rack::CommonLogger and modify the call method to ensure logging takes places only if body is data and not an asset.

module Sinatra # This need not be used. But namespacing is a good thing.

  class SilentLogger < Rack::CommonLogger

    def call(env)
      status, header, body = @app.call(env)
      began_at = Time.now
      header = Rack::Utils::HeaderHash.new(header) # converts the headers into a neat Hash

      # we will check if body is an asset and will log only if it is not an asset

      unless is_asset?(body)
        body = BodyProxy.new(body) { log(env, status, header, began_at) }
      end

      [status, header, body]

    end

    private

    def is_asset?(body)
      # If it just plain text, it won't respond to #path method
      return false unless body.respond_to?(:path)
      ext = Pathname.new(body.path).extname
      ext =~ /\.png|\.jp(g|eg)|\.js/ ? true : false
    end

  end
end

And then, in your app:

  class App < Sinatra::Base
    use Sinatra::SilentLogger

  end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top