我正在使用 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.Info("Start {job} with {@data}", job, new {a,b,c});
我使用
includeAllProperties
选项,因为每条消息可能定义不同的属性,并且我无法将它们一一预先包含为布局中的属性。
上面打印的内容类似于:
{ "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" } }
有没有办法从事件属性中分离打印的消息?因此, 实现类似
的目标{ "timestamp": "2019-09-06 13:13:40,386", "level": "Info", "message": "Start action", "job": "SomeJobType", "data": { "a": "aa", "b": "bb", "c": "cc" } }
${message:raw=true}
没有帮助,因为它打印像这样的占位符
{ "timestamp": "2019-09-06 13:13:40,386", "level": "Info", "message": "Start {job} with {@data}", "job": "SomeJobType", "data": { "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);
然后在
JsonLayout上配置
MaxRecursionLimit=1
:
<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>
另请参阅:https://github.com/NLog/NLog/wiki/EventProperties-Layout-Renderer
从您的
nlog.config
文件中删除以下行:
<attribute name="message" layout="${message}" />
然后你可以打印任何你想要的对象,就像这样:
_logger.LogInformation("{@myAnonymous}{@myOtherObject}", new
{
prop1 = "abc",
prop2 = 123,
nested =
{
nestedProp = true
}
}, myAnyTypeOfObject);
您的日志输出将如下所示(JSON 美化视图):
{
"myAnonymous": {
"prop1 ": "abc",
"prop2": 123,
"nested": {
"nestedProp": true
}
},
"myOtherObject": /*JSON representation of myAnyTypeOfObject object.*/
}
希望这有帮助。