简体   繁体   中英

Nlog JsonLayout does not include LogEvent Properties

I try to implement this example https://github.com/nlog/nlog/wiki/JsonLayout#nested-json-with-structured-logging but output in my case has no data in eventProperties field. 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"
      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();
        }
    }
}

My json output: { "time": "2022-02-09 14:21:27.7096", "level": "INFO", "message": "First: AlphaObject, Second: BetaObject", "eventProperties": { } }

Json output from example:

{
  "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
    }
  }
}

I use last nuget package of nlog and this app uses .NET framework 4.5.2. Also nlog schema highlights one of layout parameters Nlog 模式

and nlog-internal has next warn:

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 is for NLog 5.0, when using older version of NLog then one should use IncludeAllProperties (Older than 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>

Reason for changing the name is because NLog 5.0 also introduces the new option IncludeScopeProperties (And then Include All Properties becomes confusing).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM