Quantcast
Channel: SharePoint 2013 - Development and Programming forum
Viewing all articles
Browse latest Browse all 25064

What is the best way to log custom webpart code exceptions?

$
0
0

Hi,

I'm trying to log exceptions information, caused by custom code. I read that the best way should be to inherent SPDiagnosticsServiceBase  class, and write everything to ULS logs.

So I tried to do this but no new logs are appearing:

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint;
using System.Collections;
using System.Collections.Generic;
namespace BBSLogger.VisualLoggerTest
{
    public partial class VisualLoggerTestUserControl : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            var value = TextBox1.Text;            
            try
            {
                throw new System.ArgumentException("Parameter cannot be null", "original");
            }
            catch(Exception ex)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    LoggingService.LogError("WebParts", ex.Message);
                });
            }            
        }
    }
    public class LoggingService : SPDiagnosticsServiceBase
    {
        public static string MaventionDiagnosticAreaName = "Mavention";
        private static LoggingService _Current;
        public static LoggingService Current
        {
            get
            {
                if (_Current == null)
                {
                    _Current = new LoggingService();
                }
                return _Current;
            }
        }
        private LoggingService()
            : base("Mavention Logging Service", SPFarm.Local)
        {
        }
        protected override IEnumerable<SPDiagnosticsArea> ProvideAreas()
        {
            List<SPDiagnosticsArea> areas = new List<SPDiagnosticsArea>
        {
            new SPDiagnosticsArea(MaventionDiagnosticAreaName, new List<SPDiagnosticsCategory>
            {
                new SPDiagnosticsCategory("WebParts", TraceSeverity.Unexpected, EventSeverity.Error)
            })
        };
            return areas;
        }
        public static void LogError(string categoryName, string errorMessage)
        {
            SPDiagnosticsCategory category = LoggingService.Current.Areas[MaventionDiagnosticAreaName].Categories[categoryName];
            LoggingService.Current.WriteTrace(0, category, TraceSeverity.Unexpected, errorMessage);
        }
    }
}



Viewing all articles
Browse latest Browse all 25064

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>