C# NLog 自用配置

Echo_xxx發表於2024-03-31

列印到控制檯

日誌儲存到NLog目錄下

每天儲存一個資料夾

按類名儲存日誌檔案 日誌內容標註日誌等級

  • 程式碼中配置方式
        var config = new NLog.Config.LoggingConfiguration();

        // 定義檔案日誌目標
        var timeLevelClassFileTarget = new NLog.Targets.FileTarget("timeLevelClassFile")
        {
            FileName = "NLog/${shortdate}/${logger}.log",
            Layout = "${longdate} ${level:uppercase=true} ${logger} ${message} ${exception:format=tostring}"
        };
        config.AddTarget("timeLevelClassFile", timeLevelClassFileTarget);

        // 定義控制檯日誌目標
        var consoleTarget = new NLog.Targets.ColoredConsoleTarget("console")
        {
            Layout = "${date:format=HH\\:mm\\:ss} ${level:uppercase=true} ${logger} ${message} ${exception:format=tostring}",
            UseDefaultRowHighlightingRules = false
        };
        consoleTarget.RowHighlightingRules.Add(new NLog.Targets.ConsoleRowHighlightingRule("level == LogLevel.Debug", NLog.Targets.ConsoleOutputColor.Gray, NLog.Targets.ConsoleOutputColor.Black));
        consoleTarget.RowHighlightingRules.Add(new NLog.Targets.ConsoleRowHighlightingRule("level == LogLevel.Info", NLog.Targets.ConsoleOutputColor.Green, NLog.Targets.ConsoleOutputColor.Black));
        consoleTarget.RowHighlightingRules.Add(new NLog.Targets.ConsoleRowHighlightingRule("level == LogLevel.Warn", NLog.Targets.ConsoleOutputColor.Yellow, NLog.Targets.ConsoleOutputColor.Black));
        consoleTarget.RowHighlightingRules.Add(new NLog.Targets.ConsoleRowHighlightingRule("level == LogLevel.Error", NLog.Targets.ConsoleOutputColor.Red, NLog.Targets.ConsoleOutputColor.Black));
        consoleTarget.RowHighlightingRules.Add(new NLog.Targets.ConsoleRowHighlightingRule("level == LogLevel.Fatal", NLog.Targets.ConsoleOutputColor.Red, NLog.Targets.ConsoleOutputColor.White));
        config.AddTarget("console", consoleTarget);

        // 定義規則:將所有資訊級別及以上的日誌寫入檔案和控制檯
        config.LoggingRules.Add(new NLog.Config.LoggingRule("*", NLog.LogLevel.Info, timeLevelClassFileTarget));
        config.LoggingRules.Add(new NLog.Config.LoggingRule("*", NLog.LogLevel.Info, consoleTarget));

        NLog.LogManager.Configuration = config;


        var Logger = NLog.LogManager.GetCurrentClassLogger();
        Logger.Info("info");
        Logger.Debug("Debug");
        Logger.Error("Error");
        Logger.Warn("Warn");
        Logger.Fatal("Fatal");

  • appsettings配置方式
  "NLog": {
    "throwConfigExceptions": true,
    "targets": {
      "timeLevelClassFile": {
        "type": "File",
        "fileName": "NLog/${shortdate}/${logger}.log",
        "layout": "${longdate} ${level:uppercase=true} ${logger} ${message} ${exception:format=tostring}"
      },
      "console": {
        "type": "ColoredConsole",
        "layout": "${date:format=HH\\:mm\\:ss} ${level:uppercase=true} ${logger} ${message} ${exception:format=tostring}",
        "UseDefaultRowHighlightingRules": false,
        "rowHighlightingRules": [
          {
            "condition": "level == LogLevel.Debug",
            "foregroundColor": "Gray"
          },
          {
            "condition": "level == LogLevel.Info",
            "foregroundColor": "Green"
          },
          {
            "condition": "level == LogLevel.Warn",
            "foregroundColor": "Yellow"
          },
          {
            "condition": "level == LogLevel.Error",
            "foregroundColor": "Red"
          },
          {
            "condition": "level == LogLevel.Fatal",
            "foregroundColor": "Red",
            "backgroundColor": "White"
          }
        ]
      }
    },
    "rules": [
      {
        "logger": "*",
        "minLevel": "Information",
        "writeTo": "timeLevelClassFile"
      },
      {
        "logger": "*",
        "minLevel": "Information",
        "writeTo": "console"
      }
    ]
  },

  • NLog.config方式 不生效記得複製到執行目錄
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    <targets>
        <target name="timeLevelClassFile" xsi:type="File"
                fileName="NLog/${shortdate}/${logger}.log"
                layout="${longdate} ${level:uppercase=true} ${logger} ${message} ${exception:format=tostring}" />

        <target name="console" xsi:type="ColoredConsole"
                layout="${date:format=HH\\:mm\\:ss} ${level:uppercase=true} ${logger} ${message} ${exception:format=tostring}">
            <highlight-row foregroundColor="Gray" condition="level == LogLevel.Debug" />
            <highlight-row foregroundColor="Green" condition="level == LogLevel.Info" />
            <highlight-row foregroundColor="Yellow" condition="level == LogLevel.Warn" />
            <highlight-row foregroundColor="Red" condition="level == LogLevel.Error" />
            <highlight-row foregroundColor="Red" backgroundColor="White" condition="level == LogLevel.Fatal" />
        </target>
    </targets>

    <rules>
        <logger name="*" minlevel="Info" writeTo="timeLevelClassFile" />
        <logger name="*" minlevel="Info" writeTo="console" />
    </rules>
</nlog>

相關文章