如何使用thin和sinatra关闭资产请求的日志记录?

时间:2013-06-03 19:52:47

标签: logging sinatra thin sinatra-assetpack

我正在使用sinatra/assetpackthin。如何关闭为Rails记录quiet assets等资产请求?

2 个答案:

答案 0 :(得分:1)

关闭了资产:

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

然后只需在应用程序中注册它:

configure :development
  register QuietLogger
end

答案 1 :(得分:0)

Sinatra的记录器只是Rack::CommonLogger的子类。更重要的是,记录器部分是一个连接到Sinatra App的中间件。如果你有自己的基于Rack::CommonLogger模块(或你自己的中间件)的记录器实现,可以像这样添加到Sinatra:

use MyOwnLogger

我们将子类化Rack::CommonLogger并修改call方法,以确保仅在正文是数据而非资产时才进行记录。

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

然后,在你的应用中:

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

  end