在NLog中访问内存目标

时间:2014-05-23 16:34:04

标签: c# nlog

假设我的nlog.config中有以下内容(取自http://nlog-project.org/documentation/v2.0.1/html/T_NLog_Targets_MemoryTarget.htm):

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
     <targets>
         <target name="memory" xsi:type="Memory" layout="${message}" />
     </targets>

     <rules>
         <logger name="*" minlevel="Info" writeTo="memory" />
    </rules>
</nlog>

如何以编程方式访问此目标?我试图在文本框中显示日志。

4 个答案:

答案 0 :(得分:6)

这里的问题完全相同,这对我有用:

var target =(MemoryTarget)LogManager.Configuration.FindTargetByName("memory");
var log = string.Join("\r\n", target.Logs);
txtLog.Text = log;

答案 1 :(得分:3)

您可以使用LoggingConfiguration.FindTargetByName传递目标名称,然后将其强制转换为MemoryTarget,并使用Log属性获取收集的日志

答案 2 :(得分:1)

点击此处NLog手册http://nlog-project.org/documentation/v2.0.1/html/T_NLog_Targets_MemoryTarget.htm

 using System;

 using NLog;
 using NLog.Targets;

 class Example
 {
     static void Main(string[] args)
     {
        MemoryTarget target = new MemoryTarget();
        target.Layout = "${message}";
        //  target.Layout = "${longdate} ${level:uppercase=true} ${logger} ${message}";
        NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);

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

        foreach (string s in target.Logs)
        {
            Console.Write("logged: {0}", s);
        }
    }
}

答案 3 :(得分:-1)

您可以根据需要创建自己的目标和处理日志条目:https://github.com/nlog/NLog/wiki/How-to-write-a-Target