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

标签 asp.net-core .net-core nlog error-logging

我正在使用 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/

相关文章:

visual-studio - 为什么 Visual Studio 2017 找不到已安装的 .NET Core SDK?

c# - ASP.NET Core 单元测试在测试 Controller 问题响应时抛出 Null Exception

c# - 如何使用NLog将日志记录范围包括到日志文件中

sql-server - 多个实例的 Entity Framework 迁移策略

.net - 在单个解决方案中在 DNX/ASP.NET 5 项目 (project.json/xproj) 和其他 C# 项目 (csproj) 之间共享代码有哪些选项?

c# - 在面向 .NET Core 的类库包中使用 JsonConvert.DeserializeObject

c# - NLog - 删除早于 X 天的日志

c# - 为什么我的 Windows 服务不写入我的日志文件?

c# - Azure - Web 部署任务失败 [System.AggregateException - WebToolsException] ERROR_COULD_NOT_CONNECT_TO_REMOTESVC

c# - .net core 2.2 和开放的 CORS