NLog 配置 :: 控制哪些级别进入哪些输出

NLog Configuration :: Controlling Which Levels Go To Which Outputs

我正在尝试为 .NET 控制台程序配置 NLog,以将错误和致命错误记录到 Windows 事件日志中,将所有内容记录到文件中,并且仅记录真正的信息、警告、错误和致命错误控制台错误。

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" />
  </configSections>
  <startup> 
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/>
  </startup>
  <nlog autoReload="true" internalLogFile="log/internal.txt" internalLogLevel="Trace">
    <variable name="brief" value="${longdate} ${level} ${logger} ${message}${onexception:inner= ${exception:format=toString,Data}} "/>
    <variable name="verbose" value="${longdate} | ${machinename} | ${processid} | ${processname} | ${level} | ${logger} | ${message}${onexception:inner= ${exception:format=toString,Data}}"/>
    <targets>
      <target name="console" type="Console" layout="${brief}"/>
      <target name="all_in" type="File" layout="${verbose}" fileName="${basedir}/log/log.txt" archiveFileName="${basedir}/log/archive/log.{#}.txt" archiveNumbering="DateAndSequence" archiveAboveSize="1048576" archiveDateFormat="yyyyMMdd" keepFileOpen="false" encoding="iso-8859-2"/>
      <target name="events" type="EventLog" layout="${verbose}" source="nlog-test" onOverflow="Split"/>
    </targets>
    <rules>
      <logger name="*" minlevel="Info" writeTo="console"/>
      <logger name="*" minlevel="Trace" writeTo="all_in"/>
      <logger name="*" minlevel="Fatal" maxlevel="Error" writeTo="events"/>
    </rules>
  </nlog>
</configuration>

我写了一个简单的控制台程序来测试这个,它只读取用户的命令并写入适当的级别。如您所见,我还尝试启用内部日志记录,这样我就可以了解 NLog 在做什么以及为什么这样做。

这开始将错误(好)和信息(坏)写入事件日志。现在它没有向事件日志写入任何内容。我不明白为什么在 "maxlevel" 被定义为错误时将 "Info" 级别写入事件日志,显然,"Info" 是 "higher"。我也不明白为什么它停止向事件日志写入任何内容..

using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using NLog;

namespace nlog_test
{
    class Program
    {
        static Logger logger = LogManager.GetCurrentClassLogger();

        static void Main(string[] args)
        {
            while(true)
            {
                try
                {
                    Console.Write("nlog-test> ");

                    var operands = Console.ReadLine().Split(
                            new[] {' ', '\t'},
                            StringSplitOptions.RemoveEmptyEntries);

                    if(operands.Length == 0)
                    {
                        continue;
                    }

                    var command = operands[0];
                    var arguments = operands.Skip(1);
                    Action<Action<string>> log =
                            f => f(string.Join(" ", arguments));

                    switch(command)
                    {
                        case "debug":
                            log(logger.Debug);
                            break;
                        case "delete":
                            File.Delete("log/log.txt");
                            break;
                        case "error":
                            log(logger.Error);
                            break;
                        case "fatal":
                            log(logger.Fatal);
                            break;
                        case "help":
                            Console.Write(@"
COMMAND [ARG...]

Commands:

    debug TEXT...
        Delete the log file.

    delete
        Delete the log file.

    error TEXT...
        Write an error message.

    fatal TEXT...
        Write a fatal error message.

    help
        Print this message.

    info TEXT...
        Write an information message.

    print
        Print the contents of the log file.

    quit
        Exit the process.

    trace TEXT...
        Write a trace message.

    warn TEXT...
        Write a warning message.
");
                            break;
                        case "info":
                            log(logger.Info);
                            break;
                        case "print":
                            {
                                var psi = new ProcessStartInfo("less.exe", "log/log.txt");

                                //psi.CreateNoWindow = true;
                                psi.UseShellExecute = false;

                                using(var process = Process.Start(psi))
                                {
                                    process.WaitForExit();
                                }
                            }
                            break;
                        case "quit":
                            return;
                        case "trace":
                            log(logger.Trace);
                            break;
                        case "warn":
                            log(logger.Warn);
                            break;
                        default:
                            Console.Error.WriteLine(
                                    "Unknown command: {0}",
                                    command);
                            break;
                    }
                }
                catch(Exception ex)
                {
                    Console.Error.Write($"Caught unhandled exception: ");
                    Console.Error.WriteLine(ex);
                }
            }
        }
    }
}

对于 events-logging-rule,然后删除 maxlevel="Error" 并将 minlevel="Fatal" 更改为 minlevel="Error"

来自这里:

 <logger name="*" minlevel="Fatal" maxlevel="Error" writeTo="events"/>

为此:

 <logger name="*" minlevel="Error" writeTo="events"/>