Skip to content

Instantly share code, notes, and snippets.

@romanbsd
Created December 22, 2011 11:10
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save romanbsd/1509933 to your computer and use it in GitHub Desktop.
Save romanbsd/1509933 to your computer and use it in GitHub Desktop.
Color logging for Mongoid
require 'logger'
class ColoredLogger < Logger
WHITE = "\e[37m"
CYAN = "\e[36m"
MAGENTA = "\e[35m"
BLUE = "\e[34m"
YELLOW = "\e[33m"
GREEN = "\e[32m"
RED = "\e[31m"
BLACK = "\e[30m"
BOLD = "\e[1m"
CLEAR = "\e[0m"
def color(text, color, bold=false)
color = self.class.const_get(color.to_s.upcase) if color.is_a?(Symbol)
bold = bold ? BOLD : ""
"#{bold}#{color}#{text}#{CLEAR}"
end
def odd?
@odd_or_even = ! @odd_or_even
end
%w[debug info warn error fatal].each do |method|
define_method method do |message|
message = message.sub('MONGODB', color('MONGODB', odd? ? CYAN : MAGENTA)).
sub(%r{(?<=\[')([^']+)}) {|m| color(m, BLUE)}.
sub(%r{(?<=\]\.)\w+}) {|m| color(m, YELLOW)}
super(message)
end
end
end
@dbkbali
Copy link

dbkbali commented Jan 25, 2012

Would like to try it on rails 3.2, where would you initialize this i.e. which file would you save it in, I have tried an initializer and application rb, where did you place this to get it to work

@romanbsd
Copy link
Author

I packed this in gem. Just add gem 'mongoid_colored_logging' to your Gemfile

@neckhair
Copy link

The gem's name is mongoid_colored_logger, not "logging" ;-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment