Automatically log System.diagnostics.trace messages to an Nlog target

元气小坏坏 提交于 2019-12-01 03:40:38

This works for cases where there isn't an explicit source

  <system.diagnostics>
      <trace autoflush="true" indentsize="4">
        <listeners>
          <add name="MyNLogTraceListener" type="NLog.NLogTraceListener, NLog" />
          <remove name="Default" />
        </listeners>
      </trace>
  </system.diagnostics>

You can use NLog's NLogTraceListener.

For completeness, here is the System.Diagnostics configuration (from the link above) to specify the NLogTraceListener:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.diagnostics>
    <sources>
      <source name="System.Net" switchValue="All">
        <listeners>
          <add name="nlog" />
        </listeners>
      </source>
      <source name="System.Net.Sockets" switchValue="All">
        <listeners>
          <add name="nlog" />
        </listeners>
      </source>
    </sources>
    <sharedListeners>
      <add name="nlog" type="NLog.NLogTraceListener, NLog" />
    </sharedListeners>
  </system.diagnostics>
</configuration>

You also need to configure NLog to tell it how to write the information once it moves from the System.Diagnostics.Trace to NLog:

<nlog>
  <targets>
    <target name="console" type="ColoredConsole" layout="${longdate} ${windows-identity} ${message}" />
  </targets>

  <rules>
    <logger name="*" minlevel="Trace" writeTo="console" />
  </rules>
</nlog>

You might use the following in the App.config

    <system.diagnostics>

    <sources>
      <source name="System" switchValue="All">
        <listeners>
          <add name="nlog" />
        </listeners>
      </source>
    </sources>

    <sharedListeners>
      <add name="nlog" type="NLog.NLogTraceListener, NLog" />
    </sharedListeners>

    <trace autoflush="true" indentsize="4">
      <listeners>
        <add name="nlog" />
        <remove name="Default" />
      </listeners>
    </trace>

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