Enterprise Library 6.0 - Error Logging to a database

Topics: Data Access Application Block, Logging Application Block
May 2, 2013 at 7:53 PM
I'm new to enterprise library, and I'm attempting to log a test message to the local sql server database.

Yesterday, I was able to log a message to a rolling flat file, by using the Edit Server Configuration File Editor to create code for web.config and then executing the below lines of C#

using System;
using System.ComponentModel.DataAnnotations;
using System.Web.DynamicData;
using System.Diagnostics;
using System.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Logging.Database;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common;

namespace Test_Environment
public partial class _Default : System.Web.UI.Page

    protected void Page_Load(object sender, EventArgs e)
        System.Collections.IList visibleTables = Global.DefaultModel.VisibleTables;
        if (visibleTables.Count == 0)
            throw new InvalidOperationException("There are no accessible tables. Make sure that at least one data model is registered in Global.asax and scaffolding is enabled or implement custom pages.");
        Menu1.DataSource = visibleTables;

        LogEntry logEntry = new LogEntry { Message = "Error Message", Severity = TraceEventType.Error };
        Logger.SetLogWriter(new LogWriterFactory().Create());


I then used the configuration editor to create new xml code for web.config to log to a database. My config file is below.

<?xml version="1.0"?>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
<section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
  <dataConfiguration defaultDatabase="Connection String" />
  <loggingConfiguration name="" tracingEnabled="true" defaultCategory="General">
      <add name="Database Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.Database.FormattedDatabaseTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
          listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Database.Configuration.FormattedDatabaseTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
          databaseInstanceName="Connection String" writeLogStoredProcName="WriteLog"
          addCategoryStoredProcName="AddCategory" />
      <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=, 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="General">
          <add name="Database Trace Listener" />
      <allEvents switchValue="All" name="All Events" />
      <notProcessed switchValue="All" name="Unprocessed Category" />
      <errors switchValue="All" name="Logging Errors &amp; Warnings">
          <add name="Database Trace Listener" />

<compilation debug="true" targetFramework="4.5">
    <add assembly="System.Web.Entity, Version=, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
    <add assembly="System.Data.Entity, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
<pages controlRenderingCompatibilityVersion="4.0"/>

<add name="TPAReportEntities" connectionString="metadata=res://*/TPAReport.csdl|res://*/TPAReport.ssdl|res://*/TPAReport.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=AppDevVMTPA02;initial catalog=TPAReport;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient"/>
<add name="Connection String" connectionString="Database=Database;Server=(local)\SQLEXPRESS;Integrated Security=SSPI"
         providerName="System.Data.SqlClient" />

<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework"/>

My database structure was created from a script located at \Blocks\Logging\Src\DatabaseTraceListener\Scripts.

Here's my issue. I get an error in the C# code on the following line:

Logger.SetLogWriter(new LogWriterFactory().Create());

The error states that "Database provider factory not set for the static DatabaseFactory. Set a provider factory invoking the DatabaseFactory.SetProviderFactory method or by specifying custom mappings by calling the DatabaseFactory.SetDatabases method."

Please help. I'm evaluating Enterprise Library to determine if this is the logging framework my company will use for all new projects. I would like to be able to create code to log to a database before making a recommendation.
May 3, 2013 at 4:13 AM
To get past the exception you can set the DatabaseFactory:
DatabaseFactory.SetDatabaseProviderFactory(new DatabaseProviderFactory());
LogWriterFactory logWriterFactory = new LogWriterFactory();
LogEntry logEntry = new LogEntry { Message = "Error Message", Severity = TraceEventType.Error };

I would recommend reading (at least some of) the Developer’s Guide to Microsoft Enterprise Library (2nd edition) if you haven't already done so.

Randy Levy
Enterprise Library support engineer
Support How-to
May 6, 2013 at 3:12 PM
Thanks Randy.

That solved my issue.
May 9, 2013 at 8:27 PM
@Randy -
Just so you know...

The NuGet package manager for VS 2012 shows the 6.0 version by default, so if you are used to 5.0 and install the Logging Database block, you expect a certain behavior. Once you figure out that it is 6.0 and you want to downgrade a project back to 5.0, the NuGet method is either hard or broken. If you look for the Logging Database block from 5.0, it does not appear to be available any longer. So, any new project that wants to use 5.0 and log to a database presents a different type of challenge.

If there is a way to easily get back to 5.0 in a new project, this thread, or the thread on SetLogWriter might be a good place to drop in a procedure since that is what hits when you search for the resulting error.
May 12, 2013 at 7:30 AM
Version 5.0 is still on NuGet so you can use it if you wish but you are right that it's not intuitive. To get version 5, run the following command in the Package Manager Console:
Install-Package EnterpriseLibrary.Logging.Database -Version 5.0.505.0
Randy Levy
Enterprise Library support engineer
Support How-to