Check to see if an log event occurs in NLog

Deadly 提交于 2020-01-02 08:11:45

问题


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:


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>


来源:https://stackoverflow.com/questions/30848095/check-to-see-if-an-log-event-occurs-in-nlog

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!