Posted in:

Although I've built a couple of sites with ASP.NET MVC, I like the simplicity of ASP.NET Web Pages. It allows me to start with a completely empty project and only add code I've written and understand (interestingly this seems to be the philosophy behind the vNext version of ASP.NET). The downside is that every now and then I run into things that would be easy to do with ASP.NET MVC, but finding how to accomplish them with Web Pages is tricky.

Azure Diagnostics

Windows Azure WebSites offers a nice feature to turn on "application diagnostics". This allows you to write your own custom error logs using System.Diagnostics.Trace. It's super easy to configure - simply go to the control panel for your website in the Azure portal, and chose where you want these logs stored. You can choose any combination of file system, table storage and blob storage, and you can set different logging levels for each one.

clip_image001

Once you've done this, in theory you should just be able to write messages using the Trace class and see them appear in the places you’ve configured. If you choose blob storage, for example, you get a CSV file with the trace messages for a particular day.

@{
    System.Diagnostics.Trace.TraceInformation("INFORMATION");
    System.Diagnostics.Trace.TraceWarning("WARNING");
    System.Diagnostics.Trace.TraceError("ERROR");
}

Using it with ASP.NET Web Pages

However, if you try this with ASP.NET Web Pages, you simply won’t see anything at all in your logs. However, thanks to StackOverflow, I found out how to enable application tracing. Basically the TRACE flag needs to be set on the compiler this can in the web.config file. For a .NET 4.5 application, you need the following:

<system.codedom>
    <compilers>
        <compiler language="c#;cs;csharp" 
                  extension=".cs" 
                  type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" 
                  compilerOptions="/define:TRACE" 
                  warningLevel="1" /> 
    </compilers> 
</system.codedom>

Once you’ve done this, re-deploy your web.config and as if by magic all your trace statements will make it through to the configured destinations. This allows you to easily log anything from both within Razor views as well as from within any C# files you have in your App_Code folder.

Anyway, hope this post is useful to someone as it had me tearing my hair out for an evening trying to figure out why it wasn’t working.