我将 Nlog 与 .NET 核心和依赖项注入(inject)结合使用来记录 JSON 对象。
我的日志目前看起来像:{"log":{"rersourceId": "2"}} {"log":{"rersourceId": "423"}}
我希望我的日志是打印为没有消息/属性名称字段的简单 JSON 对象:{"rersourceId": "2"}{"rersourceId": "423"}
这是我的 Nlog.config:
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
internalLogLevel="info"
internalLogFile="C:\\Data\\LogFiles\\ScheduleVisits\\logging_api\\NLog.log">
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<variable name="LogBaseFolder" value="C:\\Data\\LogFiles\\ScheduleVisits\\logging_api" />
<targets>
<target name="ScheduleVisitsLogAsyncWrapper"
xsi:Type="AsyncWrapper"
batchSize="200"
queueLimit="200000"
timeToSleepBetweenBatches="0">
<target
name="ScheduleVisitsLog"
xsi:type="File"
fileName="${LogBaseFolder}\\${uppercase:${level}}\\${shortdate}.json"
archiveAboveSize="10485760"
archiveEvery="Day"
createDirs="True"
encoding="utf-8"
keepFileOpen="false"
archiveFileName ="${LogBaseFolder}\\Archive\\${uppercase:${level}}\\ScheduleVisitsAll_{#####}.zip"
archiveNumbering="DateAndSequence"
enableArchiveFileCompression="True">
<layout xsi:type="JsonLayout" includeAllProperties="True" suppressSpaces="True">
<attribute name="properties" layout="${json-event-properties}" encode="false"/>
</layout>
</target>
</target>
</targets>
<!-- rules to map from logger name to target -->
<rules>
<logger name="*"
minlevel="Trace"
writeTo="ScheduleVisitsLogAsyncWrapper">
<filters>
<when condition="starts-with('${logger}','Microsoft.')" action="Ignore" />
</filters>
</logger>
</rules>
</nlog>
在我的 Program.cs 中,我在“Main”方法中添加了这些行:
var factory = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config");
NLog.Config.ConfigurationItemFactory.Default.JsonConverter = new JsonNetSerializer();
var logger = factory.GetCurrentClassLogger();
我的 appSettings.json 文件:
{
"Environment": 1,
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Trace",
"System": "Information",
"Microsoft": "Information"
}
}
}
这就是我记录属性的方式
_logger.LogInformation("{log}", input);
我必须添加一条消息作为 LogInformation
的第一个参数,我想删除它。
最佳答案
尝试将占位符从 {log}
重命名为 {@resourceId}
并记录该属性:(不要忘记@符号)
_logger.LogInformation("{@resourceId}{@anotherResourceId}", input.YourResourceIdProperty, input.AnotherResourceIdProperty);
我不确定,但您可能还需要从 nlog.config
文件中删除以下行:
<attribute name="properties" layout="${json-event-properties}" encode="false"/>
您也可以在此处的类似帖子中查看我的回答: How to log message without even properties
关于c# - Nlog with .NET core- 如何在没有消息的情况下记录 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54852278/