具有.NET核心的Nlog-如何在不显示消息的情况下记录JSON对象

时间:2019-02-24 13:18:12

标签: c# dependency-injection .net-core nlog

我正在使用具有.NET核心和依赖项注入的Nlog来记录JSON对象。 我的日志当前看起来像:describe('Socket integration tests: ', () => { beforeAll(async done => { await apiInit(); const result = await requests.userSignIn(TEST_MAIL, TEST_PASSWORD); TEST_USER = result.user; SESSION = result.user.session; console.log('Test user authenticated succesfully.'); done(); }); beforeEach(done => { socket = io(config.socket_host, { forceNew: true }) socket.on('connect', () => { console.log('Socket connection succesful.'); socket.emit('session', { data: SESSION }, (r) => { console.log('Socket session successful.'); done(); }); }); }) test('Receiving createTag socket event?', async(done) => { console.log('API request on createTag'); const response = await Requester.post(...); console.log('API response on createTag', response); socket.on('createTag', result => { console.log('createTag socket event succesful.'); createdTagXid = result.data.xid; done(); }) }); afterEach(done => { if(socket.connected) { console.log('disconnecting.'); socket.disconnect(); } else { console.log('no connection to break'); } done(); }) } ,并且我希望将我的日志打印为简单的JSON对象,而没有消息/属性名称字段:{"log":{"rersourceId": "2"}} {"log":{"rersourceId": "423"}}

这是我的Nlog.config:

{"rersourceId": "2"}{"rersourceId": "423"}

在Program.cs中,我在“ Main”方法中添加了以下几行:

    <?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>

我的appSettings.json文件:

var factory = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config");
NLog.Config.ConfigurationItemFactory.Default.JsonConverter = new JsonNetSerializer();
var logger = factory.GetCurrentClassLogger();

这就是我记录属性的方式

{

  "Environment": 1,
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Trace",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

我必须添加一条消息作为_logger.LogInformation("{log}", input); 的第一个参数,而我想摆脱它。

2 个答案:

答案 0 :(得分:0)

尝试将占位符从{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

答案 1 :(得分:0)

什么是${json-event-properties}

您是否尝试过像这样启用maxRecursionLimit="10"

    <layout xsi:type="JsonLayout" includeAllProperties="True" suppressSpaces="True" maxRecursionLimit="10">
    </layout>

或者像这样:

    <layout xsi:type="JsonLayout" suppressSpaces="True">
           <attribute name="properties" encode="false">
               <layout xsi:type="JsonLayout" includeAllProperties="True" suppressSpaces="True" maxRecursionLimit="10" />
           </attribute>
    </layout>