Trying to create CustomExceptionLoggingHandler to log few more details into database in columns instead of just formatted message.

Topics: Exception Handling Application Block, Logging Application Block
Aug 19, 2011 at 6:10 AM

I am trying to implement custom exception handling for my application which already has exception handling through different means.

This requires few fields like ExceptionHandlingID, Call Stack and etc into a table. I got the custom logger which can log the details into table.

I am looking for some POC for creating customLoggingHandler to create log entry with above details to that my listener can logg the same into our table structure.

Thanks,

SANDHU

Aug 19, 2011 at 6:34 AM
Edited Aug 19, 2011 at 6:35 AM

Hi Sandhu,

We have a sample database tracelistener here. Kindly drop us an email if you need a copy.

 

Noel Angelo Bolasoc
Global Technologies and Solutions
Avanade, Inc.
Contact Us

 

Aug 19, 2011 at 6:45 AM
Yes, Please. But I need CustomExceptionLogger not DatabaseTraceListener. Please sent it this email.

Regards,
Mohideen



From: [email removed]
To: [email removed]
Date: Thu, 18 Aug 2011 22:34:55 -0700
Subject: Re: Trying to create Custom Logging handler to log few more details into database in columns instead ... [entlib:269642]

From: AvanadeSupport
Hi Sandhu,
We have a sample database tracelistener here. Kindly drop us an email if you want a copy.

Noel Angelo Bolasoc
Global Technologies and Solutions
Avanade, Inc.
Contact Us

Read the full discussion online.
To add a post to this discussion, reply to this email (entlib@discussions.codeplex.com)
To start a new discussion for this project, email entlib@discussions.codeplex.com
You are receiving this email because you subscribed to this discussion on CodePlex. You can unsubscribe on CodePlex.com.
Please note: Images and attachments will be removed from emails. Any posts to this discussion will also be available online at CodePlex.com
Aug 19, 2011 at 6:56 AM
I have started with below code as my handler.  I am getting below runtime error. But I came with this from a old blog, looks liks some error with customHandlerData attribute. Can some one help me with this issue.

Error:

at Microsoft

.Practices.EnterpriseLibrary.Common.Configuration.ContainerModel.RegistrationExpressionBuilder.BuildNewExpression(Type typeToBuild, NameValueCollection attributes) in c:\EntLib\Entlib\Source\Blocks.Desktop\Common\Src\Configuration\ContainerModel\RegistrationExpressionBuilder.cs:line 62

at Microsoft

.Practices.EnterpriseLibrary.Common.Configuration.ContainerModel.RegistrationExpressionBuilder.BuildExpression(Type typeToBuild, NameValueCollection attributes) in c:\EntLib\Entlib\Source\Blocks.Desktop\Common\Src\Configuration\ContainerModel\RegistrationExpressionBuilder.cs:line 37

at Microsoft

.Practices.EnterpriseLibrary.ExceptionHandling.Configuration.CustomHandlerData.<GetRegistrations>d__1.MoveNext() in c:\EntLib\Entlib\Source\Blocks.Desktop\ExceptionHandling\Src\ExceptionHandling\Configuration\CustomHandlerData.cs:line 208

at

System.Linq.Enumerable.<SelectManyIterator>d__14`2.MoveNext()

at

System.Collections.Generic.List`1.InsertRange(Int32 index, IEnumerable`1 collection)

at Microsoft

.Practices.EnterpriseLibrary.ExceptionHandling.Configuration.ExceptionHandlingSettings.GetRegistrations(IConfigurationSource configurationSource) in c:\EntLib\Entlib\Source\Blocks.Desktop\ExceptionHandling\Src\ExceptionHandling\Configuration\ExceptionHandlingSettings.cs:line 90

at Microsoft

.Practices.EnterpriseLibrary.Common.Configuration.ContainerModel.ConfigSectionLocator.<GetRegistrations>b__0(ITypeRegistrationsProvider p, IConfigurationSource cs) in c:\EntLib\Entlib\Source\Blocks.Desktop\Common\Src\Configuration\ContainerModel\ConfigSectionLocator.cs:line 60

at Microsoft

.Practices.EnterpriseLibrary.Common.Configuration.ContainerModel.ConfigSectionLocator.GetRegistrationsInternal(IConfigurationSource configurationSource, Func`3 registrationsAccessor) in c:\EntLib\Entlib\Source\Blocks.Desktop\Common\Src\Configuration\ContainerModel\ConfigSectionLocator.cs:line 88

at Microsoft

.Practices.EnterpriseLibrary.Common.Configuration.ContainerModel.ConfigSectionLocator.GetRegistrations(IConfigurationSource configurationSource) in c:\EntLib\Entlib\Source\Blocks.Desktop\Common\Src\Configuration\ContainerModel\ConfigSectionLocator.cs:line 60

at Microsoft

.Practices.EnterpriseLibrary.Common.Configuration.ContainerModel.CompositeTypeRegistrationsProviderLocator.<GetRegistrations>b__0(ITypeRegistrationsProvider l, IConfigurationSource cs) in c:\EntLib\Entlib\Source\Blocks.Desktop\Common\Src\Configuration\ContainerModel\TypeRegistrationsProvider.cs:line 128

at Microsoft

.Practices.EnterpriseLibrary.Common.Configuration.ContainerModel.CompositeTypeRegistrationsProviderLocator.<>c__DisplayClass5.<GetRegistrationsInternal>b__4(ITypeRegistrationsProvider l) in c:\EntLib\Entlib\Source\Blocks.Desktop\Common\Src\Configuration\ContainerModel\TypeRegistrationsProvider.cs:line 147

at

System.Linq.Enumerable.<SelectManyIterator>d__14`2.MoveNext()

at Microsoft

.Practices.EnterpriseLibrary.Common.Configuration.ContainerModel.Unity.UnityContainerConfigurator.RegisterAllCore(IConfigurationSource configurationSource, ITypeRegistrationsProvider rootProvider) in c:\EntLib\Entlib\Source\Blocks.Desktop\Common\Src\Configuration\ContainerModel\Unity\UnityContainerConfigurator.cs:line 61

at Microsoft

.Practices.EnterpriseLibrary.Common.Configuration.ContainerModel.ChangeTrackingContainerConfigurator.RegisterAll(IConfigurationSource configurationSource, ITypeRegistrationsProvider rootProvider) in c:\EntLib\Entlib\Source\Blocks.Desktop\Common\Src\Configuration\ContainerModel\ChangeTrackingContainerConfigurator.cs:line 68

at Microsoft

.Practices.EnterpriseLibrary.Common.Configuration.EnterpriseLibraryContainer.ConfigureContainer(ITypeRegistrationsProvider locator, IContainerConfigurator configurator, IConfigurationSource configSource) in c:\EntLib\Entlib\Source\Blocks.Desktop\Common\Src\Configuration\EnterpriseLibraryContainer.cs:line 85

at Microsoft

.Practices.EnterpriseLibrary.Common.Configuration.EnterpriseLibraryContainer.ConfigureContainer(IContainerConfigurator configurator, IConfigurationSource configSource) in c:\EntLib\Entlib\Source\Blocks.Desktop\Common\Src\Configuration\EnterpriseLibraryContainer.cs:line 66

at Microsoft

.Practices.EnterpriseLibrary.Common.Configuration.EnterpriseLibraryContainer.CreateDefaultContainer(IConfigurationSource configurationSource) in c:\EntLib\Entlib\Source\Blocks.Desktop\Common\Src\Configuration\EnterpriseLibraryContainer.cs:line 123

at Microsoft

.Practices.EnterpriseLibrary.Common.Configuration.EnterpriseLibraryContainer.CreateDefaultContainer() in c:\EntLib\Entlib\Source\Blocks.Desktop\Common\Src\Configuration\EnterpriseLibraryContainer.cs:line 108

at Microsoft

.Practices.EnterpriseLibrary.Common.Configuration.EnterpriseLibraryContainer.SetCurrentContainerIfNotSet() in c:\EntLib\Entlib\Source\Blocks.Desktop\Common\Src\Configuration\EnterpriseLibraryContainer.cs:line 95

at Microsoft

.Practices.EnterpriseLibrary.Common.Configuration.EnterpriseLibraryContainer.get_Current() in c:\EntLib\Entlib\Source\Blocks.Desktop\Common\Src\Configuration\EnterpriseLibraryContainer.cs:line 37

at PuzzlerUI

.Startup.HandleException(Exception ex, String policy) in C:\Users\mosand\Documents\Microsoft Enterprise Library 5.0 - Hands On Labs\CS\Exception Handling\exercises\ex01\begin\PuzzlerUI\Startup.cs:line 30

at PuzzlerUI

.Startup.Application_ThreadException(Object sender, ThreadExceptionEventArgs e) in C:\Users\mosand\Documents\Microsoft Enterprise Library 5.0 - Hands On Labs\CS\Exception Handling\exercises\ex01\begin\PuzzlerUI\Startup.cs:line 62

at

System.Windows.Forms.Application.ThreadContext.OnThreadException(Exception t)

at

System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

at

System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)

at

System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)

at

System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)

at

System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)

at PuzzlerUI

.Startup.Main() in C:\Users\mosand\Documents\Microsoft Enterprise Library 5.0 - Hands On Labs\CS\Exception Handling\exercises\ex01\begin\PuzzlerUI\Startup.cs:line 23

at

System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)

at Microsoft

.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()

at

System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)

at

System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)

at

System.Threading.ThreadHelper.ThreadStart()
Code:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using logg = Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
 
 
namespace MYExceptionEventListener
{
    [ConfigurationElementType(typeof(CustomHandlerData))]
    public class MYExceptionLoggingHandler : IExceptionHandler
    {
        private readonly string logCategory;
        private readonly int eventId;
        private readonly TraceEventType severity;
        private readonly string defaultTitle;
        private readonly Type formatterType;
        private readonly int minimumPriority;
        private readonly logg.LogWriter logWriter;
 
        public MYExceptionLoggingHandler(
            string logCategory,
            int eventId,
            TraceEventType severity,
            string title,
            int priority,
            Type formatterType,
            logg.LogWriter writer)
        {
            this.logCategory = logCategory;
            this.eventId = eventId;
            this.severity = severity;
            this.defaultTitle = title;
            this.minimumPriority = priority;
            this.formatterType = formatterType;
            this.logWriter = writer;
        }
 
        protected virtual void WriteToLog(string logMessage, IDictionary exceptionData)
        {
            logg.LogEntry entry = new logg.LogEntry(
                logMessage,
                logCategory,
                minimumPriority,
                eventId,
                severity,
                defaultTitle,
                null);
 
            foreach (DictionaryEntry dataEntry in exceptionData)
            {
                if (dataEntry.Key is string)
                {
                    entry.ExtendedProperties.Add(dataEntry.Key as string, dataEntry.Value);
                }
            }
 
            this.logWriter.Write(entry);
        }
 
        public Exception HandleException(Exception exception, Guid handlingInstanceId)
        {
            WriteToLog(CreateMessage(exception, handlingInstanceId), exception.Data);
            exception.Data.Add("handlingInstanceId", handlingInstanceId);
            exception.Data.Add("CallStack", exception.StackTrace);
            exception.Data.Add("ErrorMessage", exception.Message);
            return exception;
        }
 
        private string CreateMessage(Exception exception, Guid handlingInstanceID)
        {
            StringWriter writer = null;
            StringBuilder stringBuilder = null;
            try
            {
                writer = CreateStringWriter();
                ExceptionFormatter formatter = CreateFormatter(writer, exception, handlingInstanceID);
                formatter.Format();
                stringBuilder = writer.GetStringBuilder();
 
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                }
            }
 
            return stringBuilder.ToString();
        }
 
        protected virtual StringWriter CreateStringWriter()
        {
            return new StringWriter(CultureInfo.InvariantCulture);
        }
 
        private ConstructorInfo GetFormatterConstructor()
        {
            Type[] types = new Type[] { typeof(TextWriter), typeof(Exception), typeof(Guid) };
            ConstructorInfo constructor = formatterType.GetConstructor(types);
            if (constructor == null)
            {
                throw new ExceptionHandlingException("Unable to get the constructor.");
            }
            return constructor;
        }
 
        protected virtual ExceptionFormatter CreateFormatter(
            StringWriter writer,
            Exception exception,
            Guid handlingInstanceID)
        {
            ConstructorInfo constructor = GetFormatterConstructor();
            return (ExceptionFormatter)constructor.Invoke(
                new object[] { writer, exception, handlingInstanceID }
                );
        }
    }
}
 
Aug 19, 2011 at 6:58 AM

Updated the title to be clear.

Aug 19, 2011 at 7:34 AM

Hi,

Sorry for the confusion earlier. Can you tell us the exact error message? Anyway, it seems you are lacking a constructor that takes a NameValueCollection parameter (refer here for more details). Hope this helps.

 

Noel Angelo Bolasoc
Global Technologies and Solutions
Avanade, Inc.
Contact Us

Aug 19, 2011 at 9:35 AM

I went with different approach of adding the extentedProperties and reading same in traceListener. I will try the above approach and update the post.

Thanks,

Sandhu

Oct 31, 2011 at 5:39 AM

Hi,

Could you please send me the sample code of Custom exception logger to database.

My email id: pvsnmurthy.iiitb@gmail.com

Thanks in advance

 

Thanks,

Murthy

Dec 5, 2011 at 7:28 PM

hi,

even i am looking for  custom exception logger to database sample code for POC please help me out its urgents....

thanks in advance...

Feb 23, 2012 at 1:29 PM

Hi,

 

can you please send the code to kavs.as@gmail.com?

please do the needful.

Kavya

Feb 23, 2012 at 7:14 PM

Take a look at the Extended Properties Trace Listener with Custom Exception Handler solution on the Enterprise Library Sample Projects page.

The Custom Exception Handler will add all items in the exception's Data property (IDictionary) to the LogEntry's ExtendedProperties.  Also handlingInstanceId, StackTrace, and Message are added to the ExtendedProperties.


--
Randy Levy
Enterprise Library support engineer
entlib.support@live.com