Search code examples
c#exceptionenterprise-librarytracelistener

How to set databaseInstanceName in Database Trace Listener from C# code?


This might be a simple question. Is there any way by which we can set the databaseInstanceName in Database Trace Listener programitically ? As my application interacts with different databases(lets say in the connectionString tag i have 3 connection strings pointing to different DBs) so I have a requirement to log the exception in db but into respective databases. I am not supoosed to create a separate db for logging.

Is there a way ?


Solution

  • Using the fluent API to configure Enterprise Library...

    var configurationSourceBuilder = new ConfigurationSourceBuilder();
    
    // do other configuration here
    
    configurationSourceBuilder
        .ConfigureLogging()
            .LogToCategoryNamed("Category")
                .SendTo.Database("Database Trace Listener")
                    .UseDatabase("DatabaseInstance");
    
    // or here
    
    var configurationSource = new DictionaryConfigurationSource();
    configurationSourceBuilder.UpdateConfigurationWithReplace(configurationSource);
    EnterpriseLibraryContainer.Current = EnterpriseLibraryContainer.CreateDefaultContainer(configurationSource);
    

    If the reason you have three connection strings is that your program has to support running in three different environments (dev/test/production?), a better option might be to have a single connection string instead. Then deploy configuration files customized for each environment, so that the code is identical for all environments.