如何在NLog中使用网络目标记录异常 [英] How to log exceptions with network targets in NLog

查看:210
本文介绍了如何在NLog中使用网络目标记录异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 NLog 日志记录框架,并试图获取显示在任何UDP中的异常和stacktrace信息记录器应用程序,例如 Sentinel Log2Console ,但只能获取显示的日志消息部分.输出到文件的效果很好,因为大多数示例都这样做,所以问题围绕着将网络目标与NLog一起使用.

I am using the NLog logging framework and am trying to get exception and stacktrace information showing up in any UDP logger appliaction, such as Sentinel and Log2Console, but can only get the log message part displayed. Outputting to a file works well as most examples do just that, so the problem revolves around using network targets with NLog.

如果可以将自定义格式应用于内部异常和堆栈跟踪,则奖励,但这不是必需的. Exception.ToString()会走很长一段路.

Bonus if a custom format can be applied on inner exceptions and stacktrace, but this is not required. Exception.ToString() would go a long way.

注意示例代码:使用 Log2Console ,我发现了

Note on the example code: With Log2Console I found an article on how to send exception as a separate log entry. Although this worked, I was not happy with the solution.

异常记录代码示例:

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不会呈现异常

After searching some more this seems to be a limitation on NLog's end. A recent patch is apparently out there: log4jxmlevent does not render Exception

Edit2: 我用修补程序重建了NLog,但在Sentinel或Log2Console应用中似乎没有帮助.我可能必须尝试使用​​log4net来确保这些应用程序确实支持我想要实现的功能.

I rebuilt NLog with patch, but it did not seem to help in Sentinel or Log2Console apps. I might have to try log4net to make sure those apps really do support what I am trying to achieve.

Edit3: 我目前使用string.Format()自己联接和格式化消息和异常文本.效果很好,但不是我在这里想要的.

I currently use string.Format() to join and format message and exception text myself. This works well, but is not what I'm looking for here.

推荐答案

您还可以扩展NLog以包括网络日志记录的例外.

You can also extend NLog to include exceptions for network logging.

创建扩展布局:

[Layout("Log4JXmlEventLayoutEx")]    
public class Log4JXmlEventLayoutEx : Log4JXmlEventLayout
{
    protected override string GetFormattedMessage(LogEventInfo logEvent)
    {
        string msg = logEvent.Message + " ${exception:format=Message,Type,ToString,StackTrace}";
        msg = SimpleLayout.Evaluate(msg, logEvent);    
        LogEventInfo updatedInfo;
        if (msg == logEvent.Message) { 
            updatedInfo = logEvent;
        } else {
            updatedInfo = new LogEventInfo(
                logEvent.Level, logEvent.LoggerName, 
                logEvent.FormatProvider, msg, 
                logEvent.Parameters, logEvent.Exception);
        }    
        return base.GetFormattedMessage(updatedInfo);
    }
}

创建使用该布局的目标

[Target("NLogViewerEx")]
public class NLogViewerTargetEx : NLogViewerTarget
{
    private readonly Log4JXmlEventLayoutEx layout = new Log4JXmlEventLayoutEx();    
    public override Layout Layout { get { return layout; } set {} }
}

更新NLog.config:

Update NLog.config:

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <extensions>
    <add assembly="Assembly.Name.That.Contains.Extended.Target"/>
  </extensions>
  <targets>
    <target name="logViewer" 
            xsi:type="NLogViewerEx" 
            address="udp://localhost:7071">
  </targets>
 ...
</nlog>

这篇关于如何在NLog中使用网络目标记录异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆