我正在使用NLog日誌框架,並且試圖獲取任何UDP記錄器應用程序中顯示的異常和堆棧跟蹤信息,例如Sentinel和Log2Console,但只能獲取日誌消息部分顯示。輸出到一個文件的效果很好,因爲大多數例子都是這樣做的,所以這個問題圍繞着使用NLog的網絡目標展開。如何在NLog中記錄網絡目標的異常
如果可以在內部異常和堆棧跟蹤上應用自定義格式,但這不是必需的。 Exception.ToString()會走很長的路。
關於示例代碼的注意事項:使用Log2Console我發現article關於如何將異常作爲單獨的日誌條目發送。雖然這有效,但我對解決方案並不滿意。
實施例的異常記錄代碼:
Logger Log = LogManager.GetCurrentClassLogger();
try
{
throw new InvalidOperationException("My ex", new FileNotFoundException("My inner ex1", new AccessViolationException("Innermost ex")));
}
catch (Exception e)
{
Log.ErrorException("TEST", e);
}
例NLog.config:
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets async="true">
<!-- Send by UDP to Sentinel with NLogViewer protocol -->
<target name="network" xsi:type="NLogViewer" address="udp://192.168.1.3:9999" layout="${message}${onexception:inner=${newline}${exception:format=tostring}}" />
<!-- Send message by UDP to Log2Console with Chainsaw protocol -->
<target name="network2" xsi:type="Chainsaw" address="udp://192.168.1.3:9998" appinfo="Grocelist"/>
<!-- Send exception/stacktrace by UDP to Log2Console with generic network protocol -->
<target name="network2ex" xsi:type="Network" address="udp4://192.168.1.3:9998" layout="${exception:format=ToString}" />
<target name="logfile" xsi:type="File" layout="${longdate}|${level:uppercase=true}|${logger}|${message}|${exception:format=tostring}"
createDirs="true"
fileName="${basedir}/logs/${shortdate}.log"
/>
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="logfile" />
<logger name="*" minlevel="Debug" writeTo="network" />
<logger name="*" minlevel="Debug" writeTo="network2" />
<logger name="*" minlevel="Warn" writeTo="network2ex" />
</rules>
</nlog>
某些鏈接:
- http://nlog-project.org
- http://nlog-project.org/wiki/Targets
- http://nlog-project.org/wiki/Exception_layout_renderer
- http://nlog-project.org/2011/04/20/exception-logging-enhancements.html
- http://nlog-project.org/wiki/How_to_properly_log_exceptions%3F
- How to tell NLog to log exceptions?
- https://stackoverflow.com/a/9684111/134761
- http://nlog-forum.1685105.n2.nabble.com/How-to-send-stacktrace-of-exceptions-to-Chainsaw-or-Log2Console-td5465045.html
編輯: 搜索一些後,這似乎是對NLog結束的限制。最近的補丁顯然是在那裏:log4jxmlevent does not render Exception
EDIT2: 我重建NLOG補丁,但它似乎並沒有哨兵或Log2Console應用提供幫助。我可能必須嘗試使用log4net來確保這些應用程序確實支持我試圖實現的目標。
編輯3: 我目前使用string.Format()來加入並格式化消息和例外文本。這很好,但不是我在這裏尋找的。
Github上的NLogViewerTarget的源代碼顯示佈局集{}爲空操作,因此您不能覆蓋不包含例外的默認值。 – 2016-05-11 20:04:28