Last active
April 14, 2017 16:07
-
-
Save seanlinsley/4670262 to your computer and use it in GitHub Desktop.
proper logging -- with color :)
This file contains 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
# Define a setter to pass in a custom log formatter | |
class ActiveSupport::BufferedLogger | |
def formatter=(formatter) | |
@log.formatter = formatter | |
end | |
end | |
# Defines a custom log format (time, severity, message, PID, backtrace)... all with color! | |
class Formatter | |
SEVERITY_TO_TAG = {'DEBUG'=>'meh', 'INFO'=>'fyi', 'WARN'=>'hmm', 'ERROR'=>'wtf', 'FATAL'=>'omg', 'UNKNOWN'=>'???'} | |
SEVERITY_TO_COLOR = {'DEBUG'=>'37', 'INFO'=>'32', 'WARN'=>'33', 'ERROR'=>'31', 'FATAL'=>'31', 'UNKNOWN'=>'37'} | |
HUMOR_FOR_ENV = {development: true, test: true, production: false} | |
DEPTH_FOR_ENV = {development: 3, test: 3, production: 1} | |
EXCLUSION_REGEX = /log|active_support|active_record/ | |
def humorous? | |
return @is_humorous if defined? @is_humorous | |
@is_humorous = HUMOR_FOR_ENV[ Rails.env.to_sym ] | |
end | |
def depth | |
@depth ||= DEPTH_FOR_ENV[ Rails.env.to_sym ] | |
end | |
def call(severity, time, progname, msg) | |
t = time.strftime("%Y-%m-%d %H:%M:%S.") << time.usec.to_s[0..2].rjust(3) | |
color = SEVERITY_TO_COLOR[severity] | |
sev = humorous? ? "%-3s" % SEVERITY_TO_TAG[severity] # pad to at least 3 characters | |
: "%-5s" % severity # pad to at least 5 characters | |
# 2013-05-01 19:16:00.785 [omg] oh noes! (pid:30976) (admin/user.rb:45:in `block (4 levels) in <top (required)>') <- `call' <- `content_for' <- `block (2 levels) in row' <- `block in build_tag' | |
"\033[0;37m#{t}\033[0m [\033[#{color}m#{sev}\033[0m] #{msg.strip} (pid:#{$$}) #{whodunit}\033[0m\n" | |
end | |
def whodunit | |
latest, *others = caller.select{ |a| a !~ EXCLUSION_REGEX }[0, depth] | |
latest = latest[/(lib|app)\/(.*)/,-1] || latest | |
string = "" | |
string << "\033[36m(#{latest})" | |
string << "\033[35m <- " + others.map{ |s| s[/`.*/] }.join(' <- ') if others.any? | |
string | |
end | |
end | |
Rails.logger.formatter = Formatter.new |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm on Rails 4.2.8 and I had to add:
include ActiveSupport::TaggedLogging::Formatter
to the
Formatter
class.