Skip to content

Commit

Permalink
add QuietLogger that excludes pathes from Rack::CommonLogger (#1250)
Browse files Browse the repository at this point in the history
  • Loading branch information
aiomaster committed Mar 15, 2020
1 parent 0348d70 commit 00bdf4f
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 0 deletions.
3 changes: 3 additions & 0 deletions sinatra-contrib/README.md
Expand Up @@ -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`.
Expand Down
37 changes: 37 additions & 0 deletions sinatra-contrib/lib/sinatra/quiet_logger.rb
@@ -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
34 changes: 34 additions & 0 deletions sinatra-contrib/spec/quiet_logger_spec.rb
@@ -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

0 comments on commit 00bdf4f

Please sign in to comment.