Skip to content

Instantly share code, notes, and snippets.

@indirect
Last active August 29, 2015 14:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save indirect/3e703800c27df6193487 to your computer and use it in GitHub Desktop.
Save indirect/3e703800c27df6193487 to your computer and use it in GitHub Desktop.
Rails 4 silenceable logger

Rails 4 Silenceable Logger

For when you really, really don't want to log a request.

I'm using this logger to skip logging requests for CarrierWave-uploaded images in development. Loading database dumps from other environments means that the images simply aren't there in development. Rather than deal with an ActiveSupport::RoutingError and a huge 20 line backtrace per missing image, I'm just suppressing all output using this logger and a catchall route that's only active in development.

Usage

Add lib/silenceable_logger.rb to your Rails app, and adapt config/development.rb and config/routes.rb as needed.

# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
def not_found
head status: 404
end
end
# config/development.rb
require "silenceable_logger"
Rails.application.configure do |config|
config.middleware.swap Rails::Rack::Logger, SilenceableLogger,
config.log_tags, silenced: [%r{^/uploads/}]
end
# config/routes.rb
Rails.application.routes.draw do
if Rails.env.development?
# match via: :all will catch any HTTP verb
match '/uploads/*missing', via: :all, to: 'application#not_found'
end
end
# lib/silenceable_logger.rb
class SilenceableLogger < Rails::Rack::Logger
def initialize(app, taggers = nil, opts = {})
@app = app
@opts = opts
@opts[:silenced] ||= []
super(app, taggers)
end
def call(env)
if env['X-SILENCE-LOGGER'] || @opts[:silenced].any?{ |path| path === env['PATH_INFO'] }
Rails.logger.silence do
@app.call(env)
end
else
super(env)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment