如何在没有属性的情况下记录消息 [英] How to log message without even properties
问题描述
我正在使用Nlog v4.6.7,并以以下布局(在Nlog.config中)呈现消息.
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>
典型的日志记录是_logger.Info("Start {job} with {@data}", job, new {a,b,c});
我使用includeAllProperties
选项,因为每条消息可能定义了不同的属性,因此我不能一一预先将它们作为布局的属性包括在内.
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" } }
${message:raw=true}
并没有帮助,因为它像
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" } }
推荐答案
您始终可以执行以下操作:
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);
然后在 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
这篇关于如何在没有属性的情况下记录消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!