我正在使用NLog日志记录框架,并试图获取显示在任何 UDP 记录器应用程序中的异常和堆栈跟踪信息,例如Sentinel和Log2Console,但只能显示日志消息部分。与大多数示例一样,输出到文件效果很好,因此问题围绕着将网络目标与 NLog 一起使用。
如果可以将自定义格式应用于内部异常和堆栈跟踪,则有好处,但这不是必需的。Exception.ToString() 会有很长的路要走。
注意示例代码:使用Log2Console,我找到了一篇关于如何将异常作为单独的日志条目发送的文章。尽管这可行,但我对解决方案并不满意。
示例异常记录代码:
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
- 如何告诉 NLog 记录异常?
- 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,但它似乎对 Sentinel 或 Log2Console 应用程序没有帮助。我可能不得不尝试 log4net 以确保这些应用程序确实支持我想要实现的目标。
Edit3: 我目前使用 string.Format() 自己加入和格式化消息和异常文本。这很好用,但不是我在这里寻找的。