I have a config file like:
<configSections>
<section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</configSections>
<loggingConfiguration name="Logging Application Block" tracingEnabled="true" defaultCategory="Tracing" logWarningsWhenNoCategoriesMatch="true">
<listeners>
<add listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.SystemDiagnosticsTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" type="System.Diagnostics.ConsoleTraceListener, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" name="System Diagnostics Trace Listener"/>
</listeners>
<formatters>
<add template="{message}" type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="Text Formatter"/>
</formatters>
<categorySources>
<add switchValue="All" name="AppLog">
<listeners>
<add name="System Diagnostics Trace Listener"/>
</listeners>
</add>
</categorySources>
<specialSources>
<allEvents switchValue="All" name="All Events"/>
<notProcessed switchValue="All" name="Unprocessed Category"/>
<errors switchValue="Off" name="Logging Errors & Warnings"/>
</specialSources>
Besides the console listener that I have, I want to define a RollingFlatFileTraceListenerData programmatically:
var listener = new RollingFlatFileTraceListenerData("AppLog", @"c:\log.log", "", "", 0, "yyyyMMdd-hhmm", Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollFileExistsBehavior.Increment, Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollInterval.Hour, TraceOptions.LogicalOperationStack, "Text Formatter");
How can I add my newly defined listener to the list of listeners programmatically?
In general, in asp.net apps, a simple way to programmatically add TraceListeners is with the diagnostics' Trace.Listeners.Add() method. I like to do this in my global.asax.cs on Application_Start():
using D = System.Diagnostics;
...
protected void Application_Start()
{
if (D.Trace.Listeners["MyTraceListener"] == null)
{
D.Trace.Listeners.Add(new MyTraceListener("") { Name = "MyTraceListener" });
}
...
}
The only reason I check if it's already in place is because I've seen Application_Start() fire more than once, albeit infrequently.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With