Check if a log event has occurred in NLog

I am trying to check if a registration event has occurred in my application and if it does something.

I have checked everywhere and cannot find information about whether the log event has occurred.

private static Logger logger = LogManager.GetCurrentClassLogger();
logger.Info("Info Log Message");
if(logger.event == true)
{
    //an log even happen this run
}

      

+3


source to share


1 answer


It looks like you can use a target MethodCall

to accomplish this.

You can add a target record to your file NLog.config

that will route log events to a static method in one of your classes. You can find more information on how to do this in the documentation .

You can also do it directly in code like below (example copied from the documentation):

using NLog;
using NLog.Targets;
using System.Diagnostics;

public class Example
{
    public static void LogMethod(string level, string message)
    {
        Console.WriteLine("l: {0} m: {1}", level, message);
    }

    static void Main(string[] args)
    {
        MethodCallTarget target = new MethodCallTarget();
        target.ClassName = typeof(Example).AssemblyQualifiedName;
        target.MethodName = "LogMethod";
        target.Parameters.Add(new MethodCallParameter("${level}"));
        target.Parameters.Add(new MethodCallParameter("${message}"));

        NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);

        Logger logger = LogManager.GetLogger("Example");
        logger.Debug("log message");
        logger.Error("error message");
    }
}

      




I just realized that my answer is that it might not answer your question if you only want to check if a particular logger is called. If so, you can use rules to only receive events from a specific registrar, as shown in the Local Specific Routing section of the documentation.

You need to add an entry in the section of <rules>

yours NLog.config

that links to the goal that you have defined. I don't know if there is a way to customize your target code and combine it with this rule. You may need to define the target in the config file:

<targets>
    <target name="logfile" xsi:type="File" fileName="file.txt" />
</targets>

<rules>
    <logger name="SomeNamespace.Component.*" minlevel="Trace" writeTo="logfile" final="true" />
    <logger name="*" minlevel="Info" writeTo="logfile" />
</rules>

      

+4


source







All Articles