Write to ULS Logs Programmatically in SharePoint 2013/SharePoint 2010 On Premise

This is in continuation with blog I posted on “ULS logs in SharePoint 2013/SharePoint 2010 on premise

Here I would provide approach to write to ULS logs programmatically. User needs to have basic knowledge on how to open Visual Studio 2010/2012/2013 and should have basic knowledge on how to write a class.

To start with we will create a class in Visual Studio, need to paste following code to class(please make formatting changes).

//Class Starts

———————————————————————————————-

using System.Collections.Generic;
using Microsoft.SharePoint.Administration;

namespace SampleLogger.ULSLog
{
public class SampleLogger : SPDiagnosticsServiceBase
{
private const string PName= “Sample Log “;

private static SampleLogger  logger;

 private SampleLogger() : base(PRODUCTNAME + “ULS Logging Service”,            SPFarm.Local)
{}

/// <summary>
/// Here we create Log Instance
/// </summary>
private static SampleLogger loggerInstance
{
get
{
if ( samplelogger != null) return samplelogger;
else return samplelogger = new SampleLogger();
}
}

/// <summary>
/// Options to specify different Log Category under which logs will be    classified in ULS log
/// </summary>
/// <returns></returns>
protected override IEnumerable<SPDiagnosticsArea> ProvideAreas()
{
var diagnosticsCategories = new List<SPDiagnosticsCategory>
{

//One can add more categories as per requirement
new SPDiagnosticsCategory(LogCategory.ApplicationPages.ToString(),               TraceSeverity.Unexpected, EventSeverity.Error),
new SPDiagnosticsCategory(“SampleLogger Details”,                                                 TraceSeverity.Monitorable, EventSeverity.Information)
};
var areas = new List<SPDiagnosticsArea>
{
new SPDiagnosticsArea(PName, diagnosticsCategories)
};

return areas;
}

/// <summary>
/// Follwoing creates Trace Entry
/// </summary>
/// <param name=”methodName”>Method Name Object</param>
/// <param name=”traceMessage”>Log Message</param>
 public static void WritetoULS(string methodName, string traceMessage)
{
SPDiagnosticsCategory category =                                                                                    loggerInstance.Areas[PName].Categories[“SampleLogger Details”];
loggerInstance.WriteTrace(0, category, TraceSeverity.Monitorable, PName+ ” Custom::” + methodName + “::” + traceMessage);
}
}
}

———————————————————————————————-

//Class ends

Now Call the class from other location(webpart.cs, usercontrol.cs, event receivers, other class.cs) etc to use and write to ULS logs

SampleLogger.ULSLog.WritetoULS(“Your Sample details here”, “Anyother info you feel needs to be written”);

————————————–

for queries, suggestions, feedback contact me on

email :bipinparshottam@gmail.com

skype: bipin.pankhania

Advertisements