[原]Console小技巧——七彩输出

很多Console程序的输出都类似下面这张截图,黑底白字,在信息量较大的情况下很容易就将重要信息淹没在无关紧要的信息当中,给我们调试、跟踪带来了不必要的麻烦。为了解决这个问题都会将要输出的信息分级,然后过滤掉某部分无关紧要的信息,使得显示出来的信息都是比较重要的信息,例如Log4Net的Log等级。

image

Console有个 ForegroundColor 属性,按照一定的策略设置该属性就可以实现Console的七彩输出,效果如下图所示。同样恰当地设置 BackgroundColor 也会得到类似效果。

image

废话不说了,贴代码吧,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();
}
posted @ 2009-03-11 21:26  killkill  阅读(880)  评论(5编辑  收藏  举报