by Andreas

Sharepoint 2010 – Write to Sharepoint Trace Log file

Application trace logging using log4net has been covered previously several times in this blog, but I thought I’d just add another one that has been very helpful for me. Even though the Sharepoint log files (which are written to through the Unified Logging Service ULS, for those who care about details) are very crowded and hard to read, it can be a very useful tool for developers. When deploying even the simplest custom web parts and features to a production environment, some of your logic might not work as well as it did when running on the development box. And without the ability to debug, you will find yourself sitting there in the dark guessing which code line that causes the stuff-up.

So here’s a 2 minute implementation of a method that uses the ULS and writes to the standard Sharepoint 2010 log files (usually located under “Program FilesCommon FilesMicrosoft SharedWeb Server Extensions14LOGS”):

1. Create a simple method in your class

private void Log(string source, TraceSeverity traceSeverity, EventSeverity eventSeverity, string logMessage)
{
    try
    {
        SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(source, traceSeverity, eventSeverity), traceSeverity, logMessage, null);
    }
    catch (Exception)
    {
        // maybe write to Event Log?
    }
}

2. Call your method with the desired log levels

Log("MyVeryOwnEventReceiver", TraceSeverity.High, EventSeverity.Error, "God damn it, something went totally wrong!?!");

3. Find your log entry in the log file

image

Just a couple of notes:

– Beware of the log level! Your solution might have the minium log level set to higher than “Information” and your entry will not be written if your log level is set too low

– The ULS method SPDiagnosticsService.Local.WriteTrace accepts a object[] as the final parameter. I am just sending null, but this is perfect for for instance the stack trace from an exception!