如何使用NLog编写json

问题描述 投票:1回答:1

我的主要目标是使用NLog编写然后阅读以下信息。我做了以下但未能继续前进,

NLOG配置,

  <nlog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <targets>
      <target name="eventlog" xsi:type="EventLog" layout="${message}" log="Application" source="My App" />
      <target name='jsonFile' type='File' fileName='${basedir}/APILog/${date:format=yyyy-MM-dd}-webapi.json'>
        <layout type='JsonLayout'>
          <attribute name='time' layout='${longdate}' />
          <attribute name='executedby' layout='${executedby}' />
          <attribute name='username' layout='${username}' />
          <attribute name='deletedFromDB' layout='${deletedFromDB}' />
          <attribute name='deletedFromAD' layout='${deletedFromAD}' />
        </layout>
      </target>
    </targets>
    <rules>
      <logger name="*" minlevel="Trace" writeTo="eventlog" />
      <logger name="*" minlevel="Trace" writeTo="jsonFile" />
    </rules>
  </nlog>

这就是我想要读写这个文件的内容,

public class LogEntry
{
    public DateTime Time { get; set; }
    public string ExecutedBy { get; set; }
    public string username { get; set; }
    public string deletedFromDB { get; set; }
    public string deletedFromAD { get; set; }
}

var entryJson = Newtonsoft.Json.JsonConvert.SerializeObject(entry);

//看起来像这样

“{\” 时间\ “:\” 2018-03-02T11:33:55.426732 + 00:00 \”,\ “ExecutedBy \”:\ “去掉\”,\ “用户名\”:\ “EXAMPLEUSERNAME \”, \ “ExistingQAFromDB \”:\ “0 \”,\ “ExistingQAFromAD \”:\ “假\”,\ “DeletedFromDB \”:\ “真正\”,\ “DeletedFromAD \”:\ “假\”,\”状态\ “:空}”;

_logger.Debug(entryJson);

结果是......

{“时间”:“2018-03-02 11:34:01.1948”}

如何读取和写入此LogEntry对象到日志文件?

c# asp.net-web-api nlog
1个回答
1
投票

您已经在向NLog编写纯JSON了。无需激活NLog JsonLayout。

这样做:

  <target name='jsonFile' type='File' fileName='${basedir}/APILog/${date:format=yyyy-MM-dd}-webapi.json' layout='${message}' />
© www.soinside.com 2019 - 2024. All rights reserved.