Aleksandr
Aleksandr

Reputation: 13

How to count error messages in nlog from code

I'm using NLog lib for logging in my app. There is a task to count from code error and fatal messages in log-file. Is there build-in methods for it? I tried to apply {$counter}, but I couldn't use it only for error and fatal messages without printing to log-file.

Upvotes: 0

Views: 741

Answers (1)

Rolf Kristensen
Rolf Kristensen

Reputation: 19867

Curious what the number should be used for, but one way could be the 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>

And then the following code in "MyAssembly"-project:

namespace SomeNamespace
{
    using System;

    public class MyClass
    {
        static int ErrorCounter;

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

See also https://github.com/NLog/NLog/wiki/MethodCall-target

Upvotes: 1

Related Questions