Check to see if an log event occurs in NLog

2.6k views Asked by At

I am trying to check to see if a log event happens in my app, and if it does something.

I have checked everywhere and can't seem to find any info on if an log event even happens.

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

There are 1 answers

1
Jeff B On BEST ANSWER

It looks like you can use the MethodCall target to accomplish this.

You can add a target entry to your NLog.config file that would direct log events to a static method in one of your classes. See the documentation for more details on how to do that.

You can also directly do it in code as shown below (example copied here from 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 my answer about might not answer your question if you're only wanting to check if a specific logger is called. If so, you can use rules to only get events from a certain logger as shown in Logger-specific routing section of the documentation.

You'd need to add an entry to the <rules> section of your NLog.config that references the target you've defined. I don't know if there's a way to setup your target in-code and combine it with this rule. You might have 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>