Check to see if an log event occurs in NLog

时间:2015-06-15 14:43:08

标签: c# nlog

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 个答案:

答案 0 :(得分:4)

看起来您可以使用MethodCall目标来完成此任务。

您可以在NLog.config文件中添加一个目标条目,该条目将日志事件定向到您的某个类中的静态方法。有关如何执行此操作的详细信息,请参阅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");
    }
}

如果你只是想检查一个特定的记录器是否被调用,我刚刚意识到我的答案可能无法回答你的问题。如果是这样,您可以使用规则仅从特定记录器获取事件,如文档的Logger-specific routing部分所示。

您需要在引用您定义的目标的<rules> NLog.config部分添加一个条目。我不知道是否有办法在目标代码中设置目标并将其与此规则相结合。您可能必须在配置文件中定义目标:

<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>