Andrew McDonough

Colorized Logs in Ruby

October 31, 2009

Update (2019)

I wrote this post in 2009. In 2019 I believe my approach is a terrible idea. Adding methods to Ruby’s core classes (like String) is asking for trouble.

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 reada ble, 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.


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

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 toe nvironment.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.

Andrew McDonough

Andrew McDonough is a consultant CTO and software developer, currently based between Berlin and London.

Follow Andrew on Twitter or Connect on LinkedIn