| 1 | 1 | new file mode 100644 | 
| ... | ... | @@ -0,0 +1,53 @@ | 
| 0 | +--- | |
| 1 | +layout: post | |
| 2 | +title: "Colorful logging in Rails 3.2" | |
| 3 | +date: 2013-03-17 17:54 | |
| 4 | +comments: true | |
| 5 | +categories: [rails] | |
| 6 | +cover: /images/cover/avatar.png | |
| 7 | +keywords: ruby on rails, ruby, rails, logger, formatting, colors | |
| 8 | +description: Formate and colorize log output in Rails | |
| 9 | +--- | |
| 10 | + | |
| 11 | +The default Rails logger is really messy. Write somewhere ```logger.debug | |
| 12 | +some_object.inspect``` and then for an hour search where the goddamn message is | |
| 13 | +in a log file. Fortunately we can format and colorize ```logger``` output. | |
| 14 | + | |
| 15 | +Create ```config/initializers/log_formatting.rb``` file and paste this code: | |
| 16 | + | |
| 17 | +{% codeblock lang:ruby %}{% raw %} | |
| 18 | +class ActiveSupport::BufferedLogger | |
| 19 | + def formatter=(formatter) | |
| 20 | + @log.formatter = formatter | |
| 21 | + end | |
| 22 | +end | |
| 23 | + | |
| 24 | +class Formatter | |
| 25 | +    SEVERITY_TO_COLOR_MAP   = {'DEBUG'=>'33', 'INFO'=>'0;37', 'WARN'=>'36', 'ERROR'=>'31', 'FATAL'=>'31', 'UNKNOWN'=>'37'} | |
| 26 | + USE_HUMOROUS_SEVERITIES = false | |
| 27 | + | |
| 28 | + def call(severity, time, progname, msg) | |
| 29 | +        formatted_severity = sprintf("%s","#{severity}") | |
| 30 | + | |
| 31 | +        formatted_time = time.strftime("%Y-%m-%d %H:%M:%S.") << time.usec.to_s[0..2].rjust(3) | |
| 32 | + color = SEVERITY_TO_COLOR_MAP[severity] | |
| 33 | + | |
| 34 | + if msg.empty? | |
| 35 | + "\n" | |
| 36 | + else | |
| 37 | +            "\033[0;37m#{formatted_time}\033[0m [#{formatted_severity}] \033[#{color}m#{msg.strip}\033[0m\n" | |
| 38 | + end | |
| 39 | + end | |
| 40 | + | |
| 41 | +end | |
| 42 | + | |
| 43 | +Rails.logger.formatter = Formatter.new | |
| 44 | +{% endraw %}{% endcodeblock %} | |
| 45 | + | |
| 46 | +I found original code | |
| 47 | +[here](http://cbpowell.wordpress.com/2012/04/05/beautiful-logging-for-ruby-on-rails-3-2/). | |
| 48 | +I've just made small changes -- adjusted colors and formatting (and removed humorous | |
| 49 | +stuff). | |
| 50 | + | |
| 51 | +This is how it looks in ```tail -f log/development.log```: | |
| 52 | +{% img /images/rails-logger.png %} |