Created
January 4, 2012 03:21
-
-
Save jamiew/1558325 to your computer and use it in GitHub Desktop.
Rails logger customizations I use in production apps
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# config/initializers/logger_customizations.rb | |
# Production-only monkeypatches to make our logs awesome | |
# Monkeypatch 1 | |
# Don't log common poller-style requests, they are just noise | |
class CustomLogger < Rails::Rack::Logger | |
def initialize(app, opts = {}) | |
@app = app | |
@opts = opts | |
@opts[:silenced] ||= [] | |
end | |
def call(env) | |
# if env['X-SILENCE-LOGGER'] || @opts[:silenced].include?(env['PATH_INFO']) | |
if @opts[:silenced].include?(env['PATH_INFO']) | |
Rails.logger.silence do | |
@app.call(env) | |
end | |
else | |
super(env) | |
end | |
end | |
end | |
silenced_actions = if ::Rails.env.production? | |
["/notifications/unread_count.json", "/video_counts.json"] | |
else | |
[] | |
end | |
Rails.configuration.middleware.swap Rails::Rack::Logger, CustomLogger, :silenced => silenced_actions | |
# Monkeypatch round 2 | |
# * add timestamps + loglevel | |
# * skip "Rendered partial..." lines | |
module ActiveSupport | |
class BufferedLogger | |
def add(severity, message = nil, progname = nil, &block) | |
return if @level > severity | |
# Skip "Rendered..." messages in production | |
if message =~ /^Rendered/ && ::Rails.env.production? | |
return | |
end | |
# Add timestamps + severity | |
timestamp = DateTime.now.strftime("%Y-%m-%d %H:%M:%S") | |
human_severity = { | |
0 => "DEBUG", | |
1 => "INFO", | |
2 => "WARN", | |
3 => "ERROR", | |
4 => "FATAL" | |
}[severity] || "U" | |
message = (message || (block && block.call) || progname).to_s | |
if message[0] == ?\n | |
buffer << "\n" | |
auto_flush | |
message = message.strip | |
end | |
prefix = "[#{timestamp} #{human_severity}] " if ::Rails.env.production? | |
message = "#{prefix}#{message}\n" unless message[-1] == ?\n | |
buffer << message | |
auto_flush | |
message | |
end | |
end | |
end | |
I've posted a question on Stackoverflow where I've linked your gist: goo.gl/Qnimd
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, what version of Rails are you using?
I'm using Rails v3.1.10 with Cedar stack on Heroku, is it going to work "out-of-the-box"? :-)