Rails console output


TL;DR — Nothing.

Ever notice that database log entry prefixes are colored in the rails console? Ever wonder just what the cyan and magenta represent? There didn't seem to be an identifiable pattern, so I went fishing in the rails source.

It was a deep rabbit hole (because RoR is such a sprawling beast of indirection), but eventually I wound up staring at ActiveRecord::LogSubscriber#sql which is defined in log_subscriber.rb around line 33:

def sql(event)
  return unless logger.debug?

  self.class.runtime += event.duration

  payload = event.payload

  return if IGNORE_PAYLOAD_NAMES.include?(payload[:name])

  name  = "#{payload[:name]} (#{event.duration.round(1)}ms)"
  sql   = payload[:sql]
  binds = nil

  unless (payload[:binds] || []).empty?
    binds = "  " + payload[:binds].map { |attr| render_bind(attr) }.inspect
  end

  if odd?
    name = color(name, CYAN, true)
    sql  = color(sql, nil, true)
  else
    name = color(name, MAGENTA, true)
  end

  debug "  #{name}  #{sql}#{binds}"
end

So the logger chooses between the two colors based on whether or not the statement is odd? Did that mean what I thought it meant? Yep. Sure did. The definition of odd? was right below that:

def odd?
  @odd = !@odd
end

It's that simple - the logger simply toggles every other SQL statement between the two colors. The pattern was so simple I'd looked right past it. D'oh!


PS: The history and workings of video terminal colors is a huge topic in and of itself, but if you're curious, Rails uses standard ANSI escape codes and these are layed out in log_subscriber.rb around [line 39]:

# Embed in a String to clear all previous ANSI sequences.
CLEAR   = "\e[0m"
BOLD    = "\e[1m"

# Colors
BLACK   = "\e[30m"
RED     = "\e[31m"
GREEN   = "\e[32m"
YELLOW  = "\e[33m"
BLUE    = "\e[34m"
MAGENTA = "\e[35m"
CYAN    = "\e[36m"
WHITE   = "\e[37m"

UPDATE: See also More granular console SQL coloration