如何从代码中计算 nlog 中的错误消息

How to count error messages in nlog from code

我正在使用 NLog 库登录我的应用程序。有一项任务可以从日志文件中的代码错误和致命消息中计算出来。有内置方法吗?我尝试应用 {$counter},但我不能只将它用于错误和致命消息而不打印到日志文件。

想知道这个数字应该用来做什么,但一种方法可能是 MethodCall-target:

<?xml version="1.0" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <target name="m" xsi:type="MethodCall" className="SomeNamespace.MyClass, MyAssembly" methodName="LogMethod">
        <parameter layout="${level}" />
    </target>

    <rules>
        <logger name="*" minlevel="Error" writeTo="m" />
    </rules>
</nlog>

然后在"MyAssembly"-project中加入如下代码:

namespace SomeNamespace
{
    using System;

    public class MyClass
    {
        static int ErrorCounter;

        public static void LogMethod(string level)
        {
            if (level == LogLevel.Error.ToString())
               ++ErrorCounter;
        }
    }
}

另见 https://github.com/NLog/NLog/wiki/MethodCall-target