gpt4 book ai didi

asp.net-core - 将属性添加到 .net core 中 NLog 中的日志消息

转载 作者:行者123 更新时间:2023-12-04 13:57:26 25 4
gpt4 key购买 nike

我正在使用 NLog用于在 .net core 中记录消息。

我已添加 NLogStartUp.cs如下:

loggerFactory.AddNLog();

为了记录到文件,我使用以下方法:

logger.LogInformation("Message");

我想将自定义 NLog 事件属性添加到我的消息中。但是 LogInformation() 不允许我通过它。我怎样才能做到这一点?

最佳答案

如果您想要自定义布局属性(NLog 称其为布局渲染器),您可以使用 EventProperties Layout Renderer .您可以简单地在代码中执行此操作:

var logger = LogManager.GetCurrentClassLogger();
var eventInfo = new LogEventInfo(LogLevel.Info, logger.Name, "Message");
eventInfo.Properties["CustomValue"] = "My custom string";
eventInfo.Properties["CustomDateTimeValue"] = new DateTime(2020, 10, 30, 11, 26, 50);
// You can also add them like this:
eventInfo.Properties.Add("CustomNumber", 42);
// Send to Log
logger.Log(eventInfo);

然后您将能够在您的 nlog.config 中添加这些(您构成的任何属性)

<target>
<parameter name="@customtime" layout="${event-properties:CustomDateTimeValue:format=yyyy-MM-dd HH\:mm\:ss}" />
<parameter name="@customvalue" layout="${event-properties:item=CustomValue}" />
<parameter name="@customnumber" layout="${event-properties:item=CustomNumber}" />
</target>

将 NLog 与 AspNetCore 一起使用时,添加 NLog.Web Package for ASP.NET Core 很有用它为您提供了许多预定义的布局渲染器。您可以找到有关 NLog.Web for AspNetCore 的更多信息在他们的 Github 页面上。

这个 AspNetCore 包将为您提供如下内容:

<parameter name="@UserName" layout="${aspnet-user-identity}" />
<parameter name="@MvcAction" layout="${aspnet-MVC-Action}" />
<parameter name="@Session" layout="${aspnet-session:Variable=User.Name:EvaluateAsNestedProperties=true}" />
... etc

您可以在 NLog.Web.AspNetCore Github page 上找到完整列表。 .

关于asp.net-core - 将属性添加到 .net core 中 NLog 中的日志消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41958061/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com