Exception handling and Logging

Topics: Exception Handling Application Block, Logging Application Block
Jul 15, 2012 at 6:05 PM
Edited Jul 15, 2012 at 7:00 PM

EntLib 5.0

-Do I need to run some db scripts to create logging tables or can I create my own ?? examples please (videos preferred)

-Exception handling and logging samples for asp.net applications please. 

Jul 16, 2012 at 5:38 AM

1) Yes you need to run the scripts. Logging scripts can be found in "My Documents\EntLib50Src\Blocks\Logging\Src\DatabaseTraceListener\Scripts"

2) For Exception Handling simply create an Exception Policy first. You can do this by right clicking the web.config file then "Edit Enterprise Library v5 Configuration" then Blocks->Add Exception Handling Settings -> right click on "All Exceptions" -> Add handler -> Add Logging Exception Handler


You can play this tool :-) Its easy.

Exception Handling in catch block write:


.HandleException(pException, "Policy Name That you defined in configuration in above step");

 For Logging :

AppDomainName =,
MachineName =,
EventId = ,
Priority = ,
Severity = ,
Message =,
TimeStamp = ,
Title = ,,
ExtendedProperties = new Dictionary<string,Object 
ManagedThreadName =, 
ProcessName =




Jul 16, 2012 at 8:11 AM
Edited Jul 16, 2012 at 8:14 AM

Thanks for the reply... I followed the steps, but I'm stuck with logging part...

Inserting log into db is not happening.. I've create the logging db, below is my code

Logging and Exception handling code block


 var exceptionManager = EnterpriseLibraryContainer.Current.GetInstance();
                bool rethrow = exceptionManager.HandleException(ex, "DALPolicy");
                LogEntry logEntry = new LogEntry();
                logEntry.Message = "Starting up the application";
                Logger.Write("Hello Crash", "Error", 1, 01, TraceEventType.Error, "Error details");


Config FIle

<?xml version="1.0"?>

  <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
  <section name="exceptionHandling" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration.ExceptionHandlingSettings, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
  <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
 <loggingConfiguration name="LoggingApplicationBlock" tracingEnabled="true"
   <add name="Event Log Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    source="Enterprise Library Logging" formatter="Text Formatter"
    log="" machineName="." traceOutputOptions="DateTime, Callstack" />
   <add name="Database Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.Database.FormattedDatabaseTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Database.Configuration.FormattedDatabaseTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    databaseInstanceName="SqldsEntLib" writeLogStoredProcName="WriteLog"
    addCategoryStoredProcName="AddCategory" formatter="Text Formatter"
    traceOutputOptions="LogicalOperationStack, DateTime, Timestamp, ProcessId, ThreadId, Callstack"
    filter="All" />
   <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    template="Timestamp: {timestamp}{newline}&#xA;Message: {message}{newline}&#xA;Category: {category}{newline}&#xA;Priority: {priority}{newline}&#xA;EventId: {eventid}{newline}&#xA;Severity: {severity}{newline}&#xA;Title:{title}{newline}&#xA;Machine: {localMachine}{newline}&#xA;App Domain: {localAppDomain}{newline}&#xA;ProcessId: {localProcessId}{newline}&#xA;Process Name: {localProcessName}{newline}&#xA;Thread Name: {threadName}{newline}&#xA;Win32 ThreadId:{win32ThreadId}{newline}&#xA;Extended Properties: {dictionary({key} - {value}{newline})}"
    name="Text Formatter" />
   <add switchValue="All" name="DBLogging">
     <add name="Database Trace Listener" />
   <add switchValue="All" name="FileLogging">
     <add name="Event Log Listener" />
   <allEvents switchValue="All" name="All Events" />
   <notProcessed switchValue="All" name="Unprocessed Category" />
   <errors switchValue="All" name="Logging Errors &amp; Warnings">
     <add name="Event Log Listener" />
   <add name="BLPolicy" />
   <add name="DALPolicy">
     <add name="All Exceptions" type="System.Exception, mscorlib, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089"
       <add name="Logging Exception Handler" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        logCategory="DBLogging" eventId="100" severity="Error" title="Enterprise Library Exception Handling"
        formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling"
        priority="0" />
 <dataConfiguration defaultDatabase="SqldsEntLib" />
  <add name="SqldsEntLib" connectionString="Data Source=******-PC\SQL2K8R2EXPRESS;Initial Catalog=Logging;Persist Security Info=True;User ID=sa;Password=*********"
   providerName="System.Data.SqlClient" />
		<compilation debug="true" targetFramework="4.0">
		<authentication mode="Forms">
			<forms loginUrl="~/Account/Login.aspx" timeout="2880"/>
				<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/"/>
				<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
		<roleManager enabled="false">
				<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/"/>
				<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/"/>
		<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/></system.web>
		<modules runAllManagedModulesForAllRequests="true">
Jul 16, 2012 at 11:20 AM

1) Check that SA user has access to the newly created Logging Database?

2) Open  SQL Server Profiler and track if any record is going to SQL when you execute the Logging command i.e. Logger.Write("Hello Crash", "Error", 1, 01, TraceEventType.Error, "Error details");

3) In visual studio go to DEBUG -> Exceptions -> tick all Exceptions and rerun the Logging Command i.e. Logger.Write("Hello Crash", "Error", 1, 01, TraceEventType.Error, "Error details"); Because the Application Blocks supresses Exceptions and DO NOT let the developer know what is the exact cause of problem.


Feedback to the Enterprise Library Team:

Hi there Randy,

Please provide a key or some property that developers should Enable during devlopment work and disable during Release... And if the key is enabled, the Application Block shouldn't Handle exception (configuration related\connection related\Environment related or any other exceptions) and throw it.


Many Thanks,

Suraj Patnaik

Jul 16, 2012 at 6:13 PM


1> Yes it has access

2> Since I'm using express edition R2 2008 No profiler option :(

3> I'm still struggling with the 3rd option. I did check all the exceptions, but errors I'm getting are like

Procedure or function 'WriteLog' expects parameter '@customData', which was not supplied AND synchronization error.

If my understanding is correct " bool rethrow = exceptionManager.HandleException(ex, "UIPolicy");" should have thrown and error stating that it was not able to log or some stored proc error, but it didn't.


I'm still working on it.... 

Jul 16, 2012 at 6:48 PM

Some how I manged to get wrong set of scripts and executed it to create a logging DB... this in turn costed me my full day :(

So what did I do: dropped my db and recreated a new logging db....

and it worked :D


much thanks Suraj

Jul 16, 2012 at 7:02 PM

I'm able to log error into db but still I've a few conceptual and coding issues

1> var exceptionManager = EnterpriseLibraryContainer.Current.GetInstance<ExceptionManager>();

often I get this error: "Object synchronization method was called from an unsynchronized block of code"

2> bool rethrow = exceptionManager.HandleException(ex, "UIPolicy"); has not logged any error, logging is happening via Logger code Logger.Write(logEntry);     

shouldn't logging be a default exception handling part ??

Jul 17, 2012 at 9:13 AM

1) This is a known issue http://unity.codeplex.com/workitem/7019?ProjectName=unity Please ignore this.


2) The Enable Debugger should provide you the exact cause of the failure.

"3) In visual studio go to DEBUG -> Exceptions -> tick all Exceptions and rerun the Logging Command i.e. Logger.Write("Hello Crash", "Error", 1, 01, TraceEventType.Error, "Error details"); Because the Application Blocks supresses Exceptions and DO NOT let the developer know what is the exact cause of problem."

Few things to check yourself:

1) Is there any Exception Policy called "UIPolicy"?

2) Is the UIPolicy ExceptionHandler is a "Logging Exception Handler" having Listener same as you created for Database Logging? (Your case "Database Trace Listener" from the above config file)

3) Make sure all dlls related to Exception Block are added in solution as reference.

Jul 17, 2012 at 6:39 PM

Thanks for this minute level guidance....

I have traced the issue, your second point actually guided me to the trace the issue.

in the policy I had mentioned specific exception type so any other exception type was not getting logged and so no error was shown any where!


thanks a ton!

May 30, 2013 at 9:22 PM

Thank you for your suggestions.

I solved the issue by your second point.