问题
Lets say I have the following in my nlog.config (taken from 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>
How do I access this target programatically? I am trying to display the logs in a text box.
回答1:
Exactly the same issue here, this worked for me:
var target =(MemoryTarget)LogManager.Configuration.FindTargetByName("memory");
var log = string.Join("\r\n", target.Logs);
txtLog.Text = log;
回答2:
You can use LoggingConfiguration.FindTargetByName passing in the name of the target, then cast it to MemoryTarget, and use the Log property to get the logs gathered
回答3:
Check here NLog manual 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);
}
}
}
回答4:
You can create your own target and process log entries as need: https://github.com/nlog/NLog/wiki/How-to-write-a-Target
来源:https://stackoverflow.com/questions/23834330/access-memory-target-in-nlog