Logging Errors Into a Database
A Log entry is nice to have but I prefer placing exception information into a database like SQL Server. You get a couple of great benefits when you place errors into a database.
Creating an Exception Publisher
- You can centralize all of your exceptions. In the case of a Web farm you don't want the exceptions from different machines in different registries. If you log to a database, all servers in your Web farm can write to just one place.
- You can create a Web page to look up all the errors from anywhere on the Internet. You do not need to physically be on the machine where the event log resides to view your errors.
The Exception Management Application Block gives you an interface that you can implement to create your own publishera great benefit! Listing 7
shows the class you would create to implement the IExceptionPublisher interface. This class, called EMSQL, will log exceptions to a SQL Server database table.
In the above class you need to create a Publish
method that implements the IExceptionPublisher.Publish
interface. This interface requires you to accept an Exception object and two NameValueCollection parameters. The Exception object is the same object you pass from your front-end application. The NameValueCollection named additionalInfo will contain any NameValueCollection you pass such as the one you created earlier using the EMInfo class. The last argument, configSettings, is passed from the ExceptionManager class and is the XML from the web.config file that defines this publisher.
Consider the following XML that you would place into your configuration file to have the ExceptionManager call the EMSQL class's Publish
<!-- Publishes to SQL Server -->
<publisher mode="on" assembly="ErrorCommon"
This XML has four attributes: mode, assembly, type, and SQLConnect. The configSettings argument contains a name/value pair for each one of these attributes. To retrieve the SQLConnect value you would write code like the following:
strConn = configSettings.Item("SQLConnect")
You can add any attributes that you want for your publisher and then retrieve them using the Item property of the configSettings object.
After you retrieve any additional information items and your configuration file settings you can write additional code to do what you want with all of this data. In the Publish
method of the EMSQL class you will write a record into a SQL Server database using the Microsoft Data Access Application Block SqlHelper class.
The ErrorLog Table
The ErrorLog table, Listing 8
, used in the EMSQL class has just a few fields. However, you could add additional information by adding arguments to the AdditionalInfo
method of the EMInfo class and then passing them to your INSERT statement within your EMSQL class.