Tracing in MVC5

While studying for the Microsoft 70-486 certification i noticed there are two ways you can use tracing in your controller methods. The first one is by using the Trace class:

Trace.TraceInformation("View called for id = {0}", id);

When you have configured a TextWriterTracelListener this will write a line to the logfile containing the name of the executing process (in my case ‘iisexpress’, the switchvalue and the line itself.

The other way is to call a method on the TraceSource class. This will give you the opportunity to supply a name for the logger and create a dedicated configuration. The code for using a TraceSource looks like this:

TraceSource trace = new TraceSource(this.GetType().Name);
trace.TraceInformation("Index action called");

For completeness, here is the configuration as well:

      <source name="ArtworkController"             switchType="System.Diagnostics.SourceSwitch"             switchValue="Information">
          <add name="textListener" />
      <add name="textListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="D:\Projects\Logs\trace.log" traceOutputOptions="Timestamp"/>
        <add name="textListener" />

The TextWriterTraceListener that comes out of the box in .NET does not give much options to format the text. In the above configuration i added a timestamp to the trace output. The TextWriterTraceListener did not ad – as i was expecting – the timestamp on the same line, but added another line. For this reason i prefer to use a more mature logging framework like log4net.

When you need a more structured setup, you can also use the DelimitedListTraceListener. With this you can create a csv file with the trace output.

Tracing page information

Note that the old style web forms tracing is also available. You have to setup some things in the web.config to make it work:

    <trace enabled="true" mostRecent="true" pageOutput="false"/>

When this is configured you can click through the application and then point the url to http://server/sitename/trace.axd and then a page will be shown containg limited information about the last requests. In a webforms application you could use Trace.Write and the data would be written to the trace.axd result. However, in MVC this will not happen and you will need to use the tracing mechanism as described above.