EL5 Logger ConnectionString

Topics: Logging Application Block
Mar 21, 2014 at 10:21 PM
Is there a way to provide the Logger component a connectionstring at runtime rather than have it define in the web.config ?

Our security requirement dictate the password to be retrieve via PasswordVaultSDK agent which only provide the username/password at runtime.
Mar 23, 2014 at 6:11 AM
Yes, you can configure logging programmatically at runtime using either straight programmatic configuration or the fluent interface.

Is your intent to have the logging configuration in XML and then configure the database using runtime programmatic configuration? If so, then you can do that by configuring the database, and loading the configuration from the config file:
var builder = new ConfigurationSourceBuilder();

builder.ConfigureData()
        .ForDatabaseNamed("MyDB") // assume logging block configured with database name "MyDB"
            .ThatIs.ASqlDatabase()
            .WithConnectionString(@"data source=.\SQLEXPRESS;Integrated Security=SSPI;Database=Logging;User Instance=false")
            .AsDefault();

var configSource = new DictionaryConfigurationSource();
builder.UpdateConfigurationWithReplace(configSource);

IUnityContainer container = new UnityContainer();

// Load the default configuration information from the config file
container.AddNewExtension<EnterpriseLibraryCoreExtension>();

var configurator = new UnityContainerConfigurator(container);
EnterpriseLibraryContainer.ConfigureContainer(configurator, configSource);

EnterpriseLibraryContainer.Current = new UnityServiceLocator(container);
  
~~
Randy Levy
entlib.support@live.com
Enterprise Library support engineer
Support How-to
Mar 24, 2014 at 8:59 PM
Edited Mar 24, 2014 at 9:00 PM
Thanks Randy,
Bottom is a snippet of my web.config. I called the snippet of the code you shared before this routine LogExceptionDetails. But there is no entry created in the Log table. Any idea? Thanks for your help.
    public static void LogExceptionDetails(Exception exceptionToHandle)
    {
        if (exceptionToHandle == null)
        {
            throw new ArgumentNullException("exceptionToHandle", "The Exception Context is null");
        }
        else if (exceptionToHandle != null)
        {

                ELExceptionHandling.ExceptionManager entLibExceptionManager = EnterpriseLibraryContainer.Current.GetInstance<ELExceptionHandling.ExceptionManager>();

            if (string.IsNullOrEmpty(Setup.ExceptionHandlingPolicyName))
            {
                Setup.ExceptionHandlingPolicyName = "Exception Logging Policy";
            }

            entLibExceptionManager.HandleException(exceptionToHandle, Setup.ExceptionHandlingPolicyName);
        }
    }
<?xml version="1.0"?>
<configuration>
<configSections>
<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" />
</configSections>
<!--Connection Strings--> <connectionStrings>
<!-- for SQL Logging-->
<add name="LoggingDB" connectionString="Data Source=SQLVIRDEV0036\DEV36,6036;Initial Catalog=prospace_tgt;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
<!--Enterprise Library Configuration Details - Start --> <!--Logging Details--> <loggingConfiguration name="" tracingEnabled="true" defaultCategory="General">
<listeners>
  <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="LogicalOperationStack, DateTime, Timestamp, ProcessId, ThreadId, Callstack" />

  <add name="Rolling Flat File Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    rollFileExistsBehavior="Increment" rollSizeKB="50000" maxArchivedFiles="7"
    fileName="C:\MPD\LOGS\TraceLog.log" formatter="Text Formatter" traceOutputOptions="None" />

  <add name="Flat File Exception Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    fileName="C:\MPD\LOGS\ExceptionLog.log" formatter="Text Formatter" traceOutputOptions="None" />

  <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="LoggingDB" writeLogStoredProcName="WriteLog"
    addCategoryStoredProcName="AddCategory" formatter="Text Formatter"
    traceOutputOptions="None" />
</listeners>
<formatters>
  <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    template="Timestamp: {timestamp(local)}{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" />
</formatters>
<categorySources>
  <add switchValue="All" name="General">
    <listeners>
      <add name="Rolling Flat File Trace Listener" />
      <add name="Database Trace Listener" />
    </listeners>
  </add>
  <add switchValue="All" name="Exceptions">
    <listeners>
      <add name="Event Log Listener" />
      <add name="Rolling Flat File Trace Listener" />
      <add name="Flat File Exception Listener" />
      <add name="Database Trace Listener" />
    </listeners>
  </add>
</categorySources>
<specialSources>
  <allEvents switchValue="All" name="All Events" />
  <notProcessed switchValue="All" name="Unprocessed Category" />
  <errors switchValue="All" name="Logging Errors &amp; Warnings" />
</specialSources>
</loggingConfiguration>
<!--Exception Handling config--> <exceptionHandling>
<exceptionPolicies>
  <add name="Exception Logging Policy">
    <exceptionTypes>
      <add name="All Exceptions" type="System.Exception, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
        postHandlingAction="NotifyRethrow">
        <exceptionHandlers>
          <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="Exceptions" eventId="100" severity="Error" title="Enterprise Library Exception Handling"
            formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling"
            priority="0" />
        </exceptionHandlers>
      </add>
    </exceptionTypes>
  </add>
</exceptionPolicies>
</exceptionHandling>
<!--EL Database Config--> <dataConfiguration defaultDatabase="LoggingDB">
</dataConfiguration>
<!--Enterprise Library Configuration Details - End --> <!--Omit for brevity--> </configuration>
Mar 25, 2014 at 5:15 AM
Edited Mar 25, 2014 at 5:16 AM
It's hard to say what exactly is going on from the posted code and config.

You should set the errors special source to a flat file so that you can capture any errors that occur. Also, try eliminating trace listeners so that only one is called (for the database). This is for troubleshooting purposes since if one trace listener fails the others will not be executed (but the error should be captured if you configure the error special source).

Here is a complete Console application with config that should work:
using System;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ContainerModel.Unity;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.Unity;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging;
using Microsoft.Practices.EnterpriseLibrary.Logging.Database;
using Microsoft.Practices.Unity;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            BootstrapOnStartup();
            DoApplicationStuff();
        }

        static void BootstrapOnStartup()
        {
            var builder = new ConfigurationSourceBuilder();

            builder.ConfigureData()
                    .ForDatabaseNamed("MyDB")
                        .ThatIs.ASqlDatabase()
                        .WithConnectionString(@"data source=.\SQLEXPRESS;Integrated Security=SSPI;Database=Logging;User Instance=false")
                        .AsDefault();

            var configSource = new DictionaryConfigurationSource();
            builder.UpdateConfigurationWithReplace(configSource);

            IUnityContainer container = new UnityContainer();

            // Load the default configuration information from the config file
            container.AddNewExtension<EnterpriseLibraryCoreExtension>();

            var configurator = new UnityContainerConfigurator(container);
            EnterpriseLibraryContainer.ConfigureContainer(configurator, configSource);

            EnterpriseLibraryContainer.Current = new UnityServiceLocator(container);
        }

        static void DoApplicationStuff()
        {
            Exception e = new Exception("Badness!");
            ExceptionPolicy.HandleException(e, "Policy");
        }
    }
}

<?xml version="1.0"?>
<configuration>
  <configSections>
    <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" />
  </configSections>
  <loggingConfiguration name="" tracingEnabled="true" defaultCategory="General">
    <listeners>
      <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="MyDB" writeLogStoredProcName="WriteLog"
          addCategoryStoredProcName="AddCategory" />
      <add name="Flat File Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
          listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
          fileName="error.log" />
    </listeners>
    <categorySources>
      <add switchValue="All" name="General">
        <listeners>
          <add name="Database Trace Listener" />
        </listeners>
      </add>
    </categorySources>
    <specialSources>
      <allEvents switchValue="All" name="All Events" />
      <notProcessed switchValue="All" name="Unprocessed Category" />
      <errors switchValue="All" name="Logging Errors &amp; Warnings">
        <listeners>
          <add name="Flat File Trace Listener" />
        </listeners>
      </errors>
    </specialSources>
  </loggingConfiguration>
  <exceptionHandling>
    <exceptionPolicies>
      <add name="Policy">
        <exceptionTypes>
          <add name="All Exceptions" type="System.Exception, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
              postHandlingAction="NotifyRethrow">
            <exceptionHandlers>
              <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="General" eventId="100" severity="Error" title="Enterprise Library Exception Handling"
                  formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling"
                  priority="0" />
            </exceptionHandlers>
          </add>
        </exceptionTypes>
      </add>
    </exceptionPolicies>
  </exceptionHandling>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  </startup>
</configuration>

If you are still having issues then posting a small sample application would help.

~~
Randy Levy
entlib.support@live.com
Enterprise Library support engineer
Support How-to
Mar 25, 2014 at 5:09 PM
It was a an issue in my ConnectionString. I missed the Integrated Security=True attr.
"Data Source=ServerName\InstanceName;Initial Catalog=CatalogName;Integrated Security=True; User ID=XXXXXX; Password=XXXXXXXX"

Thanks.
Marked as answer by davidnguy on 3/25/2014 at 9:09 AM