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);
}
}
}