本文介绍了检查是否在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
}

推荐答案

您似乎可以使用MethodCall目标来完成此任务.

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

您可以将目标条目添加到NLog.config文件中,该目标条目会将日志事件定向到您的一个类中的静态方法.有关如何执行此操作的更多详细信息,请参见文档.

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.

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

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>

这篇关于检查是否在NLog中发生了日志事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 13:39