How to log message without even properties

空扰寡人 提交于 2020-01-16 09:02:49

问题


I am using Nlog v4.6.7 and render messages with the following layout (in 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>

A typical logging is _logger.Info("Start {job} with {@data}", job, new {a,b,c});

I use the includeAllProperties option since each message may define different properties and I cannot pre-include them one by one as attributes in the layout.

What ends to be printed by the above is something like:

{ "timestamp": "2019-09-06 13:13:40,386", "level": "Info", "message": "Start \"SomeJobType\" with {\"a\":\"aa\", \"b\":\"bb\", \"c\":\"cc\"}", "job": "SomeJobType", "data": { "a": "aa", "b": "bb", "c": "cc" } }

Is there a way to disengage the message printed from the event-properties? Thus, achieve something like

{ "timestamp": "2019-09-06 13:13:40,386", "level": "Info", "message": "Start action", "job": "SomeJobType", "data": { "a": "aa", "b": "bb", "c": "cc" } }

The ${message:raw=true} does not help since it prints the placeholders like

{ "timestamp": "2019-09-06 13:13:40,386", "level": "Info", "message": "Start {job} with {@data}", "job": "SomeJobType", "data": { "a": "aa", "b": "bb", "c": "cc" } }


回答1:


You can always do this:

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);

And then configure MaxRecursionLimit=1 on JsonLayout:

 <layout xsi:type="JsonLayout" includeAllProperties="true" maxRecursionLimit="1">
      <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>

See also: https://github.com/NLog/NLog/wiki/EventProperties-Layout-Renderer




回答2:


Remove the line below from your nlog.config file:

<attribute name="message" layout="${message}" />

Then you can print any object you want, just like this:

_logger.LogInformation("{@myAnonymous}{@myOtherObject}", new 
{ 
   prop1 = "abc", 
   prop2 = 123,
   nested = 
   {
      nestedProp = true
   }
}, myAnyTypeOfObject);

Your log output will look like this (JSON beautified view):

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

Hope this helps.



来源:https://stackoverflow.com/questions/57823205/how-to-log-message-without-even-properties

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!