Logging Exceptions to Database

Topics: Logging Application Block
Nov 15, 2010 at 4:55 AM

Hi

Can anyone send me a sample for logging Exceptions to the default DB - Logging? . I am using a .Net windows client.

Thanks

Tutumon

Nov 15, 2010 at 5:10 AM
Edited Nov 15, 2010 at 5:14 AM

There's no difference in the code that you will use when logging to a database or when you're logging to a file or event log.  You must just have the correct configuration.  Add a database trace listener and specify the name of the connection string for the Logging database in the Database Instance Name property.  Associate it to a category and use it for any log entries you want to be logged in the database.  Associate that category then to a Logging Exception Handler.  If you're using EntLib 5.0, the configuration tool, it includes a Log Exceptions to Database wizard under the Wizard menu.  It guides you to the step by step process of configuring this.  Let me know if you need additional information.

Sarah Urmeneta
Global Technologies and Solutions
Avanade, Inc.
entlib.support@avanade.com

Nov 15, 2010 at 5:34 AM

Hi,

Thanks for your mail

i have configured the application in the followingg way. Please check whether this is the correct configuration.

<configuration>
  <configSections>
    <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
    <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
  </configSections>
  <loggingConfiguration name="Logging Application Block" tracingEnabled="true"
    defaultCategory="" logWarningsWhenNoCategoriesMatch="true">
    <listeners>
      <add databaseInstanceName="Power" writeLogStoredProcName="WriteLog"
        addCategoryStoredProcName="AddCategory" formatter="" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Database.Configuration.FormattedDatabaseTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
        traceOutputOptions="None" type="Microsoft.Practices.EnterpriseLibrary.Logging.Database.FormattedDatabaseTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
        name="Power Listener" />
    </listeners>
    <formatters>
      <add template="Timestamp: {timestamp}&#xD;&#xA;Message: {message}&#xD;&#xA;Category: {category}&#xD;&#xA;Priority: {priority}&#xD;&#xA;EventId: {eventid}&#xD;&#xA;Severity: {severity}&#xD;&#xA;Title:{title}&#xD;&#xA;Machine: {machine}&#xD;&#xA;Application Domain: {appDomain}&#xD;&#xA;Process Id: {processId}&#xD;&#xA;Process Name: {processName}&#xD;&#xA;Win32 Thread Id: {win32ThreadId}&#xD;&#xA;Thread Name: {threadName}&#xD;&#xA;Extended Properties: {dictionary({key} - {value}&#xD;&#xA;)}"
        type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
        name="Text Formatter" />
    </formatters>
    <categorySources>
      <add switchValue="All" name="Audit" />
    </categorySources>
    <specialSources>
      <allEvents switchValue="All" name="All Events" />
      <notProcessed switchValue="All" name="Unprocessed Category" />
      <errors switchValue="All" name="Logging Errors &amp; Warnings" />
    </specialSources>
  </loggingConfiguration>
  <dataConfiguration defaultDatabase="Power" />
  <connectionStrings>
    <add name="Power" connectionString="Database=Logging;Server=(local)\SQLEXPRESS;Integrated Security=SSPI"
      providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

And i need  to log the exception in my application in the catch block

I have a code block like the bellow

 public static string ConnectionKey
        {
            get
            {
                try
                {
                    return ConfigurationManager.AppSettings[CONNECTION_KEY];
                }
                catch (Exception ex)
                {
                    // I have to log exception from here.
                }
                return null;
            }
        }

I have to log the exception from the catch block. How do i log from there?

Thanks

TutuMon 

Nov 15, 2010 at 5:58 AM

You didn't define an exception policy with a logging exception handler in your config.  You should add the exceptionHandling configuration section, add a policy, and add the Logging Exception Handler to it.  In its Categories property, add the Audit category.  By the way, your Audit category doesn't have any referenced trace listener.  You should add the Power Listener to it, use the configuration tool rather than manually editing the xml.  For the sake of validation on your side, this is how it should look in the xml editor.

<categorySources>
       <add switchValue="All" name="Audit">
                <listeners>
                    <add name="Power Listener" />
                </listeners>
       </add>
</categorySources>

I also suggest specifying a value for the Formatter property of the Database Trace listener.  I think there was a bug in a previous version of EntLib (not sure what is the specific version) wherein logging to database fails if you don't specify a value for the Formatter property.

Finally, the code you should add in the catch block is

bool rethrow = ExceptionPolicy.HandleException(ex, exceptionPolicyName);
if(rethrow)
{
     throw;
}

where exceptionPolicyName is the name of the exception policy you defined in your config.

Hope this helps.

 

Sarah Urmeneta
Global Technologies and Solutions
Avanade, Inc.
entlib.support@avanade.com

Nov 16, 2010 at 10:11 AM

HI

Superb. I have closed all those issues with your help. I have one more question pending on the Enterprises Library configuration.

I have environment related config files. I am picking the environment related settings like this

 <appSettings file="Dev.config">
  <add key="DataConfiguration.ActiveLocation" value="Development" />
 </appSettings>

and the keys and values will come from my Dev.config file for the development settings. Now we have the connectionstring section.

<connectionStrings>
        <add name="Development" connectionString="Database=Logging;Server=Test\SQLSRV1;user id=admin;password=u(&376ly"
            providerName="System.Data.SqlClient" />

       <add name="Staging" connectionString="Database=Logging;Server=Test\SQLSRV2;user id=admin;password=u(&376ly"
            providerName="System.Data.SqlClient" />
        <add name="Production" connectionString="Database=Logging;Server=Test\SQLSRV3;user id=admin;password=u(&376ly"
            providerName="System.Data.SqlClient" />


</connectionStrings>

I want my application to pick the connectionstring based on the key DataConfiguration.ActiveLocation in the app settings. How do i do that? How do i cahnge my name section in the name part?

Thanks

Tutu

Nov 17, 2010 at 12:00 AM

Are you using Environmental Overrides?  What you want is not something that can be automated using Enterprise Library.  In fact, environmental overrides only provides you the option to define values for different environment and generate the corresponding configuration file.  It is still up to you to deploy the correct configuration file.

You need to come up with your own custom code to accomplish what you want.  I'm not also sure why do you have a  Dev.config but your connectionStrings section provides different connection string for the various environments.  Shouldn't each one be just present in their corresponding config file? (e.g. Development connection string be placed in Dev.config)

By the way, please create a new discussion thread for a question pertaining to a  different topic.

Sarah Urmeneta
Global Technologies and Solutions
Avanade, Inc.
entlib.support@avanade.com