c# - Nlog JsonLayout 不包含 LogEvent 属性

标签 c# json .net nlog

我尝试实现这个例子https://github.com/nlog/nlog/wiki/JsonLayout#nested-json-with-structured-logging但在我的例子中,输出在 eventProperties 字段中没有数据。 NLog配置:

    <?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"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="true"
      throwExceptions="false"
      internalLogLevel="TRACE" internalLogFile="c:\temp\nlog-internal.log">


  <variable name="LogLevel" value="DEBUG"/>
  <variable name="brief" value="${longdate} | ${level} | ${logger} | ${message}"/>
  <variable name="verbose" value="${longdate} | ${machinename} | ${processid} | ${processname} | ${level} | ${logger} | ${message}"/>
  <variable name="logLifetime"  value="3"/>



  <targets>
    <target name="Global" xsi:type="File" fileName="Logs/GlobalLog.txt"  archiveNumbering="Date" enableArchiveFileCompression="true" archiveFileName="Archive/IPSlog.{#}.zip" archiveDateFormat="yyyy-MM-dd"
        maxArchiveDays="${logLifetime}"
       archiveEvery="Day" >
    <layout xsi:type="JsonLayout">
      <attribute name="time" layout="${longdate}" />
      <attribute name="level" layout="${level:upperCase=true}"/>
      <attribute name="message" layout="${message}" />
      <attribute name="eventProperties" encode="false" >
        <layout xsi:type='JsonLayout' includeEventProperties="true"  maxRecursionLimit="2"/>
      </attribute>
    </layout>
    </target>
    <target name="Color" xsi:type="Console">
      <layout xsi:type="JsonLayout">
        <attribute name="time" layout="${longdate}" />
        <attribute name="level" layout="${level:upperCase=true}"/>
        <attribute name="message" layout="${message}" />
        <attribute name="eventProperties" encode="false" >
          <layout xsi:type='JsonLayout' includeEventProperties="true"  maxRecursionLimit="2"/>
        </attribute>
      </layout>
    </target>
  </targets>
  
  

  <rules>
    <logger name="Global" minlevel="${LogLevel}"  writeTo="Global,Color" />
    
  </rules>
</nlog>

c#:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp5
{
    [Serializable]
    public class TestObject
    {
        public string A { get; set; }
        public int B { get; set; }

        public override string ToString() { return A; }
    }

    class Program
    {
        private static readonly NLog.Logger Logger = NLog.LogManager.GetLogger("Global");
        static void Main(string[] args)
        {
            var testObj = new TestObject
            {
                A = "AlphaObject",
                B = 2
            };

            var testObjB = new TestObject
            {
                A = "BetaObject",
                B = 3
            };

            Logger.Info("First: {alpha}, Second: {beta}", testObj, testObjB);
         
            Console.ReadLine();
        }
    }
}

我的json输出:{ "time": "2022-02-09 14:21:27.7096", "level": "INFO", "message": "First: AlphaObject, Second: BetaObject", “事件属性”:{ } }

示例的 Json 输出:

{
  "time": "2018-04-02 02:00:00.2349",
  "level": "Info",
  "message": "First: AlphaObject, Second: BetaObject",
  "eventProperties": {
    "alpha": {
      "A": "AlphaObject",
      "B": 2
    },
    "beta": {
      "A": "BetaObject",
      "B": 3
    }
  }
}

我使用 nlog 的最后一个 nuget 包,此应用程序使用 .NET Framework 4.5.2。 nlog 模式还突出显示布局参数之一 Nlog schema

nlog-internal 有下一个警告:

Warn Error has been raised. Exception: NLog.NLogConfigurationException: Error when setting value 'true' for property 'includeEventProperties' on element 'NLog.Config.NLogXmlElement' ---> System.NotSupportedException: Parameter includeEventProperties not supported on JsonLayout
   в NLog.Internal.PropertyHelper.SetPropertyFromString(Object obj, String propertyName, String value, ConfigurationItemFactory configurationItemFactory)
   в NLog.Config.LoggingConfigurationParser.ConfigureObjectFromAttributes(Object targetObject, ILoggingConfigurationElement element, Boolean ignoreType)
   --- Конец трассировки внутреннего стека исключений ---

最佳答案

IncludeEventProperties 适用于 NLog 5.0,当使用旧版本的 NLog 时,应使用 IncludeAllProperties(早于 NLog v4.7.14)

      <layout xsi:type="JsonLayout">
        <attribute name="time" layout="${longdate}" />
        <attribute name="level" layout="${level:upperCase=true}"/>
        <attribute name="message" layout="${message}" />
        <attribute name="eventProperties" encode="false" >
          <layout xsi:type='JsonLayout' includeAllProperties="true"  maxRecursionLimit="2"/>
        </attribute>
      </layout>

更改名称的原因是因为 NLog 5.0 还引入了新选项 IncludeScopeProperties (然后 IncludeAllProperties 就变得困惑了)。

关于c# - Nlog JsonLayout 不包含 LogEvent 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71049928/

相关文章:

c# - ViewBag 和 HtmlHelper 错误 : "One or more types required to compile a dynamic expression cannot be found. Are you missing an assembly reference?"

json - 在golang中解析变量中的Json

json - 解析 Alamofire json 响应

.net - Azure 应用程序服务 Api 应用程序中的 netFrameworkVersion

c# - 另存为 PNG 时文件为空

c# - VS WPF设计器: how to add control from referenced project to a form in the main project

c# - 在 Scala 中实现 ExpandoObject

json - Echarts处理大量数据时无法呈现平滑的线条

c# - 如何使用 C# 执行 PowerShell 脚本

c# - 如何在 SQL Server 中使用 SMO 删除和重新创建主键索引?