C# 如何记录没有偶数属性的消息

C# 如何记录没有偶数属性的消息,c#,nlog,C#,Nlog,我正在使用Nlog v4.6.7,并在Nlog.config中以以下布局呈现消息 <layout xsi:type="JsonLayout" includeAllProperties="true"> <attribute name="timestamp" layout="${date:universalTime=true:format=yyyy-MM-dd HH\:mm\:ss,fff}" /> <attribute name="level

我正在使用Nlog v4.6.7,并在Nlog.config中以以下布局呈现消息

 <layout xsi:type="JsonLayout" includeAllProperties="true">
      <attribute name="timestamp" layout="${date:universalTime=true:format=yyyy-MM-dd HH\:mm\:ss,fff}" />
      <attribute name="level" layout="${level}"/>
      <attribute name="message" layout="${message}" />
 </layout>
典型的日志记录是_logger.InfoStart{job},带有{@data},job,new{A,b,c}

我使用includeAllProperties选项,因为每条消息可能定义不同的属性,并且我不能将它们逐个预包含为布局中的属性

上面要打印的内容类似于:

{时间戳:2019-09-06 13:13:40386,级别:Info,消息:Start\SomeJobType\与{\a\:\aa\,\b\:\bb\,\c\:\cc\},作业:SomeJobType,数据:{a:aa,b:bb,c:cc}

是否有方法将打印的消息与事件属性分离?因此 达到某种程度

{时间戳:2019-09-06 13:13:40386,级别:信息,消息:开始操作,作业:SomeJobType,数据:{a:aa,b:bb,c:cc}

${message:raw=true}不起作用,因为它打印的占位符如下


{时间戳:2019-09-06 13:13:40386,级别:Info,消息:用{@data}开始{job},作业:SomeJobType,数据:{a:aa,b:bb,c:cc}

您可以随时这样做:

var logger = NLog.LogManager.GetCurrentClassLogger();
var theEvent = new NLog.LogEventInfo(NLog.LogLevel.Info, null, "Start action");
theEvent.Properties["job"] = job;
theEvent.Properties["data"] = new {a,b,c};
logger.Log(theEvent);
然后在以下位置配置MaxRecursionLimit=1:


另请参见:

从nlog.config文件中删除以下行:

您的日志输出将如下所示:

{
    "myAnonymous": {
        "prop1 ": "abc",
        "prop2": 123,
        "nested": {
            "nestedProp": true
        }
    },
    "myOtherObject": /*JSON representation of myAnyTypeOfObject object.*/
}

希望这有帮助。

您是否尝试创建loggerEvent?!有了它,您可以编辑属性并根据需要处理它们。您可以使用${message:raw=true}而不是使用${message:raw=true}。另请参见@RolfKristensen感谢您提供的提示,但正如我在消息中所写,此解决方案不是我正在寻找的解决方案,因为if打印占位符。@PedroBrito实际上,我的代码最终记录了一个NLog.LogEventInfo,它接受MessageTemplateParameter的lsit。我一开始没有使用它,因为我想知道是否有一个更符合实际的解决方案。不过,我想我会尝试一下。MessageTemplateParameter构造函数是一种特殊的优化,用于与Microsoft扩展日志中的消息解析器集成。考虑使用LogEvestFiels.属性参见下面的答案
<attribute name="message" layout="${message}" />
_logger.LogInformation("{@myAnonymous}{@myOtherObject}", new 
{ 
   prop1 = "abc", 
   prop2 = 123,
   nested = 
   {
      nestedProp = true
   }
}, myAnyTypeOfObject);
{
    "myAnonymous": {
        "prop1 ": "abc",
        "prop2": 123,
        "nested": {
            "nestedProp": true
        }
    },
    "myOtherObject": /*JSON representation of myAnyTypeOfObject object.*/
}