I have a command line program, which outputs logging to the screen.
I want error lines to show up in red. Is there some special character codes I can output to switc
You can read here a good and illustrated article: http://kpumuk.info/ruby-on-rails/colorizing-console-ruby-script-output/
I think setting console text color is pretty language-specific. Here is an example in C# from MSDN:
for (int x = 0; x < colorNames.Length; x++)
{
Console.Write("{0,2}: ", x);
Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), colorNames[x]);
Console.Write("This is foreground color {0}.", colorNames[x]);
Console.ResetColor();
Console.WriteLine();
}
Console.ForegroundColor is the property for setting text color.
Ultimately you need to call SetConsoleTextAttribute. You can get a console screen buffer handle from GetStdHandle.
On windows, you can do it easily in three ways:
require 'win32console'
puts "\e[31mHello, World!\e[0m"
Now you could extend String with a small method called red
require 'win32console'
class String
def red
"\e[31m#{self}\e[0m"
end
end
puts "Hello, World!".red
Also you can extend String like this to get more colors:
require 'win32console'
class String
{ :reset => 0,
:bold => 1,
:dark => 2,
:underline => 4,
:blink => 5,
:negative => 7,
:black => 30,
:red => 31,
:green => 32,
:yellow => 33,
:blue => 34,
:magenta => 35,
:cyan => 36,
:white => 37,
}.each do |key, value|
define_method key do
"\e[#{value}m" + self + "\e[0m"
end
end
end
puts "Hello, World!".red
Or, if you can install gems:
gem install term-ansicolor
And in your program:
require 'win32console'
require 'term/ansicolor'
class String
include Term::ANSIColor
end
puts "Hello, World!".red
puts "Hello, World!".blue
puts "Annoy me!".blink.yellow.bold
Please see the docs for term/ansicolor for more information and possible usage.
on ANSI escape codes:
32-bit character-mode (subsystem:console) Windows applications don't write ANSI escape sequences to the console
They must interpret the escape code actions and call the native Console API instead
Thanks microsoft :-(
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Console_Test
{
class Program
{
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.WriteLine("Hello World");
Console.ReadKey();
}
}
}
You can change the color using a simple C# program, http://powerof2games.com/node/31 describes how you can wrap console output to achieve the effect.
color [background][foreground]
Where colors are defined as follows:
0 = Black 8 = Gray
1 = Blue 9 = Light Blue
2 = Green A = Light Green
3 = Aqua B = Light Aqua
4 = Red C = Light Red
5 = Purple D = Light Purple
6 = Yellow E = Light Yellow
7 = White F = Bright White
For example, to change the background to blue and the foreground to gray, you would type:
color 18