Colorized Logs in Ruby

The logger is a really useful way to tell what is going on in your ruby application, but in Rails, it can be difficult to spot your own log entries when they are mixed up with all the ActiveRecord and ActionController ones.  One way of making your own comments stand out is to use color in your logs. You have probably noticed that Rails does this already to make the logs more readable, and the effect is fairly easy to replicate yourself. Color in the terminal is achieved using ANSI escape codes, a series of characters to tell the terminal to print the enclosed string in a particular color and style. You could just include this in your logs yourself, but this ends up looking a bit messy. To solve this, I extended String to include a method called colorize. It takes a color (”gray”,”red”, “green”, “yellow”, “blue”, “magenta”, “cyan”,”white”) and a few other optional parameters for styling.

colorize.rb:

class String
  def colorize(color, options = {})
    background = options[:background] || options[:bg] || false
    style = options[:style]
    offsets = ["gray","red", "green", "yellow", "blue", "magenta", "cyan","white"]
    styles = ["normal","bold","dark","italic","underline","xx","xx","underline","xx","strikethrough"]
    start = background ? 40 : 30
    color_code = start + (offsets.index(color) || 8)
    style_code = styles.index(style) || 0
    "\e[#{style_code};#{color_code}m#{self}\e[0m"
  end
end

Here are some examples of colorize in action:

> irb
irb(main):001:0> require 'colorize'
irb(main):002:0> s = "Some text"
irb(main):003:0> puts s.colorize "red"
Some text
irb(main):004:0> puts s.colorize "green", :bg => true
Some text
irb(main):005:0> puts s.colorize "blue", :style => "underline"
Some text
irb(main):006:0> puts s.colorize "magenta", :style => "bold"
Some text
irb(main):007:0> puts s.colorize "cyan", :style => "strikethrough"
Some text
irb(main):008:0> puts s.colorize "yellow", :style => "dark"
Some text

To include this in your Rails app, and use it with the debugger, just put the code in a place where it will be loaded.  My method of doing this is to drop colorize.rb into your application’s /lib directory, then add the following line to environment.rb

require File.join(File.dirname(__FILE__), '../lib/colorize')

Reload the server, then you will be able to add color to your logs e.g.

logger.debug("This is a message for debugging".colorize("red"))

As well as using colorize in logs, you can also use it in any script that runs on the command line. Uses for this might include test reporting, installation scripts, sysadmin script reporting and others.

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">