Question

Is it possible to retrieve records from ULS log using C#/SharePoint API without having to manually parse log files? I would like to display logged messages on a custom web page, and I would like to filter these messages beforehand (based on area, category etc.). Ideally, it should be as simple as binding log records to a grid where Area=someValue.

There is plenty written about how to write to ULS log (using SPDiagnosticsServiceBase), but I can't find anything on how to read it. In SP2013, there is SPULSRetriever, but nothing similar seems to exist in SP2010.

UPDATE As suggested by the answer, here's one way to do it by invoking powershell.

using (PowerShell ps = PowerShell.Create())
{                
    ps.AddScript("Add-PSSnapin \"Microsoft.SharePoint.PowerShell\"");

    // example: call "Get-SPLogEvent -StartTime (Get-Date).AddHours(-24) | Where-Object {$_.Area -eq 'SharePoint Foundation'}" to get log records of last 24 hours
    string script = String.Format("Get-SPLogEvent -StartTime (Get-Date).AddHours(-24)");
    ps.AddScript(script);
    ps.AddCommand("where-object");
    ps.AddParameter("filterscript", ScriptBlock.Create("$_.Area -eq 'SharePoint Foundation'"));                             
    Collection<PSObject> output = ps.Invoke();

    foreach (PSObject outputItem in output)
    {
        if (outputItem != null)
        {                    
            // Display logged messages.
            Console.WriteLine(outputItem.Members["Message"].Value);                     
        }
    }
}
Was it helpful?

Solution

One quick way would be to have the C# program call PowerShell cmdlets to read the ULS log files and then use the results to display on a custom web page. The SharePoint PowerShell cmdlets (e.g., Get-SPLogEvent & Get-SPLogLevel) would provide the 'filtering' as needed -

Executing PowerShell scripts from C#

How to run PowerShell scripts from C#

Using Windows Powershell Cmdlets with ULS Logging

Logging and events cmdlets (SharePoint 2010)

Using Get-SPLogEvent to retrieve logs based on correlation id

Get-SPLogEvent (PowerShell cmdlet)

Get-SPLogLevel (PowerShell cmdlet)

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top