How to log exceptions with network targets in NLog

别来无恙 提交于 2019-12-04 05:03:47

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

Create an extended layout:

[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);
    }
}

Create a target that uses that layout

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

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>

I had this problem, and just updated my NLog nuget package to 2.0.1.2

Now I have exceptions coming through to Log2Console just fine.

A few years later and this is pretty trivial, try adding

includeSourceInfo="true"

to your target file, so it looks like;

 <target name="viewer"
            xsi:type="NLogViewer"
            includeSourceInfo="true"
            address="udp://127.0.0.1:9999" />

Gives you Source File, Line, Class and Method info.

Have you tried the latest developer snapshot of Chainsaw? It will display stack traces and supports log4net/UDP appenders, and according to NLog you can use it as well: http://nlog-project.org/wiki/Chainsaw_target

Try the latest developer snapshot, has a ton of features: http://people.apache.org/~sdeboy

Just download and build the latest (NLog-Build-2.0.0.2007-0-g72f6495) sources from GitHub: https://github.com/jkowalski/NLog/tree/ This issue is fixed there by NLog developer.

In your NLog.config modify the target like the following.

<target name="file" xsi:type="File" fileName="log.txt" layout="${longdate}:${message} ${exception:format=message,stacktrace:separator=*}" /> 

The part that you are looking for is

${exception:format=message,stacktrace:separator=*}

For more information on this look here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!