很多Console程序的輸出都類似下面這張截圖,黑底白字,在信息量較大的情況下很容易就將重要信息 淹沒在無關緊要的信息當中,給我們調試、跟蹤帶來了不必要的麻煩。為了解決這個問題都會將要輸出的 信息分級,然後過濾掉某部分無關緊要的信息,使得顯示出來的信息都是比較重要的信息,例如Log4Net 的Log等級。
Console有個 ForegroundColor 屬性,按照一定的策略設置該屬性就可以實現Console的七彩輸出,效 果如下圖所示。同樣恰當地設置 BackgroundColor 也會得到類似效果。
廢話不說了,貼代碼吧,OldLog方法是模擬傳統的輸出,黑底白字。NewLog方法是模擬七彩輸出的。
class Logger
{
public static void OldLog(Level level, string message)
{
Console.WriteLine
(
string.Format
(
"[{0}][{1}]\t{2}",
level.ToString(),
DateTime.Now.ToString(),
message
)
);
}
private static Mutex mutex = new Mutex();
public static void NewLog(Level level, string message)
{
mutex.WaitOne();
SetConsoleColor(level);
Console.WriteLine
(
string.Format
(
"[{0}][{1}]\t{2}",
level.ToString(),
DateTime.Now.ToString(),
message
)
);
ResetConsoleColor();
mutex.ReleaseMutex();
}
private static void SetConsoleColor(Level level)
{
switch (level)
{
case Level.Info: Console.ForegroundColor = ConsoleColor.Green;
break;
case Level.Debug: Console.ForegroundColor = ConsoleColor.Blue;
break;
case Level.Warning: Console.ForegroundColor = ConsoleColor.Yellow;
break;
case Level.Error: Console.ForegroundColor = ConsoleColor.Red;
break;
case Level.Fatal: Console.ForegroundColor = ConsoleColor.White;
Console.BackgroundColor = ConsoleColor.Red;
break;
default: Console.ForegroundColor = ConsoleColor.Cyan;
break;
}
}
private static void ResetConsoleColor()
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.BackgroundColor = ConsoleColor.Black;
}
}
Main方法分別調用Logger類的兩個方法。
static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
Logger.OldLog(Level.Info, "It is INFO message");
Logger.OldLog(Level.Debug, "It is DEBUG message");
Logger.OldLog (Level.Warning, "It is WARNING message");
Logger.OldLog(Level.Error, "It is ERROR message");
Logger.OldLog(Level.Fatal, "It is FATAL message");
}
Console.ReadLine();
Console.Clear();
for (int i = 0; i < 10; i++)
{
Logger.NewLog(Level.Info, "It is INFO message");
Logger.NewLog(Level.Debug, "It is DEBUG message");
Logger.NewLog (Level.Warning, "It is WARNING message");
Logger.NewLog(Level.Error, "It is ERROR message");
Logger.NewLog(Level.Fatal, "It is FATAL message");
}
Console.ReadLine();
}