Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log System.Diagnostics.Trace and System.Diagnostics.Debug messages to NLog file?

Tags:

c#

nlog

I'm supporting a large, old application. The code uses NLog as well as Debug.WriteLine and Trace.WriteLine. I'm trying to redirect the Debug.WriteLine and the Trace.WriteLine to the Nlog file. So that everything is in one place. At the moment, some is in the Output window and some is in the log file.

I followed this article to use the NLogTraceListener

That article has System.Net and System.Net.Sockets getting shunted to the log file. I tried it and it works. I see System.Net and System.Net.Sockets messages getting logged to the file. This SO article describes the same -- and it works.

What doesn't work is logging my own messages from my own namespaces and classes to the log file.

System.Diagnostics.Debug.WriteLine("This won't end up in the log file");
System.Diagnostics.Trace.WriteLine("This won't end up in the log file");

I've tried changing the source names to namespaces from my app. Didn't work. I cannot get my own WriteLines to log to the file. They still appear in the Visual Studio output window.

For instance:

    <system.diagnostics>
        <sources>
            <source name="MyAppNamespace" switchValue="All">
                <listeners>
                    <add name="nlog" />
                </listeners>
            </source>
        </sources>
        <sharedListeners>
            <add name="nlog" type="NLog.NLogTraceListener, NLog" />
        </sharedListeners>
    </system.diagnostics>

The explicit NLog calls are logging to the log file just fine:

NLog.LogManager.GetCurrentClassLogger().Trace("This Works");
like image 627
101010 Avatar asked Oct 03 '13 21:10

101010


1 Answers

You've configured a TraceSource to log to NLog, but your trace statement isn't using that TraceSource.

Try:

<system.diagnostics>
    <trace>
      <listeners>
          <add name="nlog" type="NLog.NLogTraceListener, NLog" />
      </listeners>
    </trace>
</system.diagnostics>

Or use the TraceSource you've configured, for example:

TraceSource source = new TraceSource("MyAppNamespace");
source.TraceEvent(TraceEventType.Warning, 2, "File Test not found");
like image 180
Joe Avatar answered Sep 23 '22 02:09

Joe