首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

Console 進階技巧 (二):七彩輸出與分級日誌實現

     編輯:關於.NET

預設 Console 黑底白字在資訊密集時極難辨識關鍵日誌。本文展示如何利用 Console.ForegroundColor / BackgroundColor 實現分級彩色輸出,並封裝為執行緒安全的 Logger 類,效果堪比 Log4Net 控制台輸出。

效果對比

傳統單色輸出:
單色

七彩分級輸出:
七彩

核心實現:Logger 類

public enum Level { Info, Debug, Warning, Error, Fatal }

public static class Logger {
    private static readonly Mutex mutex = new Mutex(); // 多執行緒同步

    // 傳統單色輸出
    public static void OldLog(Level level, string message) {
        Console.WriteLine($"[{level}][{DateTime.Now}]\t{message}");
    }

    // 七彩輸出 (執行緒安全)
    public static void NewLog(Level level, string message) {
        mutex.WaitOne();
        try {
            SetConsoleColor(level);
            Console.WriteLine($"[{level}][{DateTime.Now}]\t{message}");
        } finally {
            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.Gray; // 預設灰白
        Console.BackgroundColor = ConsoleColor.Black;
    }
}

測試驗證

static void Main() {
    // 單色測試
    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();
}

設計亮點

  1. Mutex 保證原子性:防止多執行緒交錯導致顏色狀態污染 (如執行緒 A 設紅色未重置,執行緒 B 繼承紅色)。
  2. try/finally 確保重置:異常時也能恢復預設顏色,避免後續輸出顏色錯亂。
  3. 枚舉驅動策略:新增日誌等級只需擴充 Level 與 switch,符合開放封閉原則。
  4. Fatal 雙色強調:白字紅底最高視覺權重,關鍵錯誤一眼可見。

進階擴展建議

  • 背景色替代方案:對於色盲友善,可改用背景色區分等級 (如 Info=綠底, Error=紅底)。
  • 輸出重導向:結合 Console.SetOut 將日誌同時寫入檔案,檔案版去除 ANSI 色碼。
  • 結構化日誌:輸出 JSON 格式,配合 jq/ELK 分析。
  • 現代替代:.NET Core 3.0+ 建議直接使用 Microsoft.Extensions.Logging + ConsoleLogger 內建支援 ANSI 色碼與分級。

適用場景

  • 無法引入第三方日誌庫的輕量專案
  • CI/CD 腳本關鍵步驟高亮
  • 互動式 CLI 工具狀態提示
  • 教學演示 Console 進階特性

七彩輸出雖小,卻能大幅降低除錯認知負荷,是 Console 開發者的必備技能。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved