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

后端 未结 3 1075
眼角桃花
眼角桃花 2021-01-11 09:25

Say you have C# trace messages all over an application. Something like:

Trace.TraceInformation(\"Service Started\"); 

How do you aut

相关标签:
3条回答
  • 2021-01-11 10:06

    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>
    
    0 讨论(0)
  • 2021-01-11 10:15

    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>
    
    0 讨论(0)
  • 2021-01-11 10:15

    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>
    
    0 讨论(0)
提交回复
热议问题