c# - NLog在C#中获取消息

标签 c# nlog

我最近在一个 ASP.Net 项目中为一个客户使用 Nlog,并取得了很好的成功。我需要连接到具有自己的事件日志管理的现有应用程序,并向他们提供我的日志信息的副本。

有什么方法可以使用任何日志函数获取我提供给 Nlog 的字符串吗?

例子:

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

如何获取字符串“My info”、“My debug”、“My error”和“My warn”作为数组或列表<>?

最佳答案

您可以使用 MemoryTarget为此:

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;

消息是字符串,从nlog.config 中的layout 属性呈现

API docs for MemoryTarget

如果您需要将它们写入另一个组件,我建议创建一个 custom target

关于c# - NLog在C#中获取消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44933339/

相关文章:

c# - 无法将使用 NLog 的库发布到 NuGet

c# - 拥有不同配置的 NLog 记录器

c# - aspnet-sessionId 不适用于 Asp.Net Core

c# - 有人可以解释一下这段 HtmlAgilityPack 代码吗?

c# - 无法将 ref enum 转换为 ref dynamic?

c# - 如何切换到显示为弹出窗口的框架

c# - 生成 Word 文档的缩略图

c# - .NET5辅助服务模板的NLog设置

c# - ILogger 未将 TRACE 和 DEBUG 消息写入目标

c# - Linq 其中值在数组中