I'm surprised I wasn't able to find this on SO already.
I want to be able to color specific segments of strings in my log output that goes to the console. So somethng like this:
"This part of the message in Green: This part in Blue"
Possibly written like this:
Rails.logger.debug("This part of the message in Green: ".green + "This part in Blue".blue)
Basically what you want to do is embed ANSI escape sequences for color into your debug strings, just like you would in a regular Ruby program. There are several ways to go about this:
Use the rainbow
gem, which allows you to do this:
require 'rainbow'
Rails.logger.debug(Rainbow("This message is Green").green)
or require
the mixin to add methods directly to the string class:
Updated March 2021: The Rainbow Gem API has changed. Use this now:
require 'rainbow/refinement'
using Rainbow
Rails.logger.debug("This is Green - ".green + "This is Blue".blue)
Previous Version (for posterity):
require 'rainbow/ext/string'
Rails.logger.debug("This is Green - ".green + "This is Blue".blue)
End Update
The Rainbow gem will automatically add the beginning and ending escape sequences to the string.
Use the colorize
gem, which does the same thing as the rainbow mixin to the String class:
require 'colorize'
Rails.logger.debug("This is Green - ".green + "This is Blue".blue)
Put the escape sequences in yourself, using something like this:
Rails.logger.debug("\033[32mThis message is Green\033[0m")
Write your own extension to the String class. See this answer or this answer for an example.
For more ideas, see How can I use Ruby to colorize the text output to a terminal?
Since Rails 5, it is possible to use the internal support for coloring sql logs via ActiveSupport::LogSubscriber
:
logger.debug ActiveSupport::LogSubscriber.new.send(:color, "message", :red)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With