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 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
| # Define a setter to pass in a custom log formatter | |
| class ActiveSupport::BufferedLogger | |
| def formatter=(formatter) | |
| @log.formatter = formatter | |
| end | |
| end | |
| # Define a custom log format (time, severity, message, PID, caller trace)... all with color! | |
| class Formatter | |
| SEVERITY_TO_TAG = {'DEBUG'=>'meh', 'INFO'=>'fyi', 'WARN'=>'hmm', 'ERROR'=>'wtf', 'FATAL'=>'omg', 'UNKNOWN'=>'???'} | |
| SEVERITY_TO_COLOR = {'DEBUG'=>'0;37', 'INFO'=>'32', 'WARN'=>'33', 'ERROR'=>'31', 'FATAL'=>'31', 'UNKNOWN'=>'37'} | |
| HUMOR_FOR_ENV = {development: true, test: true, production: false} | |
| def humorous? | |
| return @is_humorous if defined? @is_humorous | |
| @is_humorous = HUMOR_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] | |
| : "%-5s" % severity | |
| # Using the full backtrace, we attempt to identify the line of code that called us. | |
| # Show a shortened file path if possible. Else, show the full path. | |
| full_path = caller.detect{ |a| !(a =~ /log|active_support|active_record/) } | |
| whodunit = full_path[/(lib|app).*/] || full_path | |
| # 2013-01-29 19:48:16.976 [fyi] Served asset /active_admin.js - 304 Not Modified (3ms) (pid:6878) (lib/sprockets/server.rb:58:in `call') | |
| "\033[0;37m#{t}\033[0m [\033[#{color}m#{sev}\033[0m] #{msg.strip} (pid:#{$$}) \033[36m(#{whodunit})\033[0m\n" | |
| 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::Formatterto the
Formatterclass.