问题
I am recently using Nlog in an ASP.Net project for a client with good success. I need to connect to an existing application that has its own event log management and provide them with a copy of my log information.
Is there any way to get the strings that I provided to Nlog using any of the log functions?
Example:
logger.Info("My info");
logger.Debug("My debug");
logger.Error("My error");
logger.Warn("My warn");
List<string> messages = logger.getStrings() <-- this is what I need
How I can get strings "My info", "My debug", "My error" and "My warn" as an array or List<>?
回答1:
You could use the MemoryTarget for it:
nlog.config:
<nlog internalLogFile="c:\tempp\nlog-internal.log" internalLogLevel="Info">
<targets>
<target xsi:type="Memory" name="target1" layout="${message}" />
</targets>
<rules>
<logger name="*" writeTo="target1" />
</rules>
</nlog>
C#:
var target = LogManager.Configuration.FindTargetByName<MemoryTarget>("target1");
IList<string> messages = target.Logs;
The messages are strings
, rendered from the layout
attribute in nlog.config
API docs for MemoryTarget
If you need to write them to another component, I would recommend to create a custom target
来源:https://stackoverflow.com/questions/44933339/nlog-get-messages-in-c-sharp