views:

293

answers:

1

I have a web application where I would like to add or edit Enterprise Library logging at runtime. I'm familiar with how to configure EntLib Logging completely programmatically and through the config file, but I would like to use a combination of the two. I'd like to have some base TraceListeners setup via the config file, but then at application startup, I'd like to conditionally add some Email TraceListeners depending on some other user settings stored in a database.

My current solution is to open the web.config as a Configuration object, and modify the web.config sections by hand, but I'm wondering if there's a way to programmatically add TraceListeners to the currently configured LogWriter (or whichever) classes.

Any suggestions?

+1  A: 

You need to create an EmailTraceListener and then add it to the collection of TraceSources for your Category.

In this example I have a base trace listener pointing to a flat file.

  <add fileName="trace.log" header="----------------------------------------"
    footer="----------------------------------------" formatter="Text Formatter"
    listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    traceOutputOptions="None" filter="All" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    name="FlatFile TraceListener" />

With a category source as the following:

   <categorySources>
      <add switchValue="All" name="General">
        <listeners>
          <add name="FlatFile TraceListener" />
        </listeners>
      </add>
    </categorySources>

Then using code I am able to add an EmailTraceListener to the TraceSources collection.

    var emailTraceListener = new EmailTraceListener("[email protected]", "[email protected]", "Food", "Bar",
                                                    "smtp.foo.bar") {Name = "EmailTraceListener"};
    LogSource logSource;
    Logger.Writer.TraceSources.TryGetValue("General", out logSource);
    logSource.Listeners.Add(emailTraceListener);


    var logEntry = new LogEntry {Message = "Test"};
    Logger.Write(logEntry);

Running this example then will produce an email with the LogEntry information as well as an entry in the log file trace.log

Mark
Perfect, exactly what I was looking for. Thanks
Andy White