add QuietLogger that excludes pathes from Rack::CommonLogger (#1250)
This commit is contained in:
parent
0348d701ad
commit
00bdf4faee
|
@ -67,6 +67,9 @@ Currently included:
|
|||
* [`sinatra/test_helpers`][sinatra-test-helpers]: Helper methods to ease testing your Sinatra
|
||||
application. Partly extracted from Sinatra. Testing framework agnostic
|
||||
|
||||
* `sinatra/quiet_logger`: Extension to exclude specific pathes from access log.
|
||||
It works by patching Rack::CommonLogger
|
||||
|
||||
## Installation
|
||||
|
||||
Add `gem 'sinatra-contrib'` to *Gemfile*, then execute `bundle install`.
|
||||
|
|
|
@ -0,0 +1,37 @@
|
|||
module Sinatra
|
||||
# = Sinatra::QuietLogger
|
||||
#
|
||||
# QuietLogger extension allows you to define pathes excluded
|
||||
# from logging using the +quiet_logger_prefixes+ setting.
|
||||
# It is inspired from rails quiet_logger, but handles multiple pathes.
|
||||
#
|
||||
# == Usage
|
||||
#
|
||||
# You have to require the quiet_logger, set the setting
|
||||
# and register the extension in your application.
|
||||
#
|
||||
# require 'sinatra/base'
|
||||
# require 'sinatra/quiet_logger'
|
||||
#
|
||||
# set :quiet_logger_prefixes, %w(css js images fonts)
|
||||
#
|
||||
# class App < Sinatra::Base
|
||||
# register Sinatra::QuietLogger
|
||||
# end
|
||||
module QuietLogger
|
||||
|
||||
def self.registered(app)
|
||||
quiet_logger_prefixes = app.settings.quiet_logger_prefixes.join('|') rescue ''
|
||||
return warn('You need to specify the pathes you wish to exclude from logging via `set :quiet_logger_prefixes, %w(images css fonts)`') if quiet_logger_prefixes.empty?
|
||||
const_set('QUIET_LOGGER_REGEX', %r(\A/{0,2}(?:#{quiet_logger_prefixes})))
|
||||
::Rack::CommonLogger.prepend(
|
||||
::Module.new do
|
||||
def log(env, *)
|
||||
super unless env['PATH_INFO'] =~ QUIET_LOGGER_REGEX
|
||||
end
|
||||
end
|
||||
)
|
||||
end
|
||||
|
||||
end
|
||||
end
|
|
@ -0,0 +1,34 @@
|
|||
require 'spec_helper'
|
||||
require 'sinatra/quiet_logger'
|
||||
require 'logger'
|
||||
|
||||
describe Sinatra::QuietLogger do
|
||||
|
||||
it 'logs just pathes not excluded' do
|
||||
log = StringIO.new
|
||||
logger = Logger.new(log)
|
||||
mock_app do
|
||||
use Rack::CommonLogger, logger
|
||||
set :quiet_logger_prefixes, %w(quiet asset)
|
||||
register Sinatra::QuietLogger
|
||||
get('/log') { 'in log' }
|
||||
get('/quiet') { 'not in log' }
|
||||
end
|
||||
|
||||
get('/log')
|
||||
get('/quiet')
|
||||
|
||||
str = log.string
|
||||
expect(str).to include('GET /log')
|
||||
expect(str).to_not include('GET /quiet')
|
||||
end
|
||||
|
||||
it 'warns about not setting quiet_logger_prefixes' do
|
||||
expect {
|
||||
mock_app do
|
||||
register Sinatra::QuietLogger
|
||||
end
|
||||
}.to output("You need to specify the pathes you wish to exclude from logging via `set :quiet_logger_prefixes, %w(images css fonts)`\n").to_stderr
|
||||
end
|
||||
|
||||
end
|
Loading…
Reference in New Issue