Adding log to ULS and also adding to sharepoint list
// adding log to ULS log
public class ULSLogService : SPDiagnosticsServiceBase
{
private static string PRODUCT_NAME = "Biraj_Blog";
private ULSLogService() : base("Biraj Logging
Service", SPFarm.Local) { }
private static ULSLogService logSerivce;
public static ULSLogService LogSerivce
{
get
{
if (logSerivce == null)
{
logSerivce = new ULSLogService();
}
return logSerivce;
}
}
protected override IEnumerable<SPDiagnosticsArea> ProvideAreas()
{
List<SPDiagnosticsArea> areas = new List<SPDiagnosticsArea>{
new SPDiagnosticsArea(PRODUCT_NAME, new List<SPDiagnosticsCategory>{
new SPDiagnosticsCategory("Biraj_Info", TraceSeverity.Verbose, EventSeverity.Information),
new SPDiagnosticsCategory("Biraj_Error", TraceSeverity.Unexpected, EventSeverity.Warning),
})
};
return areas;
}
public static void DisplayInfo(string ClassMethodName, Exception ex)
{
SPDiagnosticsCategory category = ULSLogService.LogSerivce.Areas[PRODUCT_NAME].Categories["Biraj_Info"];
ULSLogService.LogSerivce.WriteTrace(0, category, TraceSeverity.Verbose,
ClassMethodName + " \n-- " + ex.TargetSite + "
\n-- " + ex.Message + " \n-- " +
ex.StackTrace + " \n-- " + ex.Source + "
\n-- " + ex.Data);
Logs.AddIntoList("Info", ClassMethodName, ex);
}
public static void DisplayError(string ClassMethodName, Exception ex)
{
SPDiagnosticsCategory category = ULSLogService.LogSerivce.Areas[PRODUCT_NAME].Categories["Biraj_Error"];
ULSLogService.LogSerivce.WriteTrace(0, category, TraceSeverity.Unexpected,
ClassMethodName + " \n-- " + ex.TargetSite + "
\n-- " + ex.Message + " \n-- " +
ex.StackTrace + " \n-- " + ex.Source + "
\n-- " + ex.Data);
Logs.AddIntoList("Error", ClassMethodName, ex);
}
}
// adding log to SharePoint List
public static void AddIntoList(string Title, string ClassMethodName, Exception exception)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite spSite = new SPSite(SPContext.Current.Web.Url))
{
using (SPWeb spWeb = spSite.OpenWeb())
{
try
{
spWeb.AllowUnsafeUpdates = true;
SPList logsList =
spWeb.Lists.TryGetList("Logs");
SPListItem newItem =
logsList.Items.Add();
newItem["Title"] =
Title;
newItem["MethodName"] =
ClassMethodName;
newItem["TargetSite"] =
exception.TargetSite;
newItem["Message"] =
exception.Message;
newItem["Source"] =
exception.Source;
newItem["StackTrace"] =
exception.StackTrace;
newItem["Data"] =
exception.Data;
newItem.Update();
spWeb.AllowUnsafeUpdates = false;
}
catch(Exception ex)
{
}
}
}
});
}
catch (Exception ex)
{
}
}
No comments:
Post a Comment