NLog get messages in C#

﹥>﹥吖頭↗ 提交于 2019-12-24 11:44:57

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!