Click here to Skip to main content
15,887,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi.

I am looking at the Enterprise Library 5.0 logging application block and am having a bit of trouble with adding a rolling flat file trace listener at runtime using the fluent configuration API. My intention is to add new trace listeners to the existing configuration at runtime and have different messages logged out to different files.

At design time I set up my App.Config file with a default category and trace listener as follows:

XML
<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" />
    </configSections>
    <loggingConfiguration name="Logging Application Block" 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="None" />
            <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"
                fileName="MyDefaultRolling.log" formatter="Text Formatter"
                rollFileExistsBehavior="Increment" rollInterval="Minute" rollSizeKB="40000"
                timeStampPattern="yyyy-MM-dd HH-mm-ss" maxArchivedFiles="4"
                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}{newline}Message: {message}{newline}Category: {category}{newline}Priority: {priority}{newline}EventId: {eventid}{newline}Severity: {severity}{newline}Title:{title}{newline}ProcessId: {localProcessId}{newline}Process Name: {localProcessName}{newline}Thread Name: {threadName}{newline}Win32 ThreadId:{win32ThreadId}{newline}"
                name="Text Formatter" />
        </formatters>
        <categorySources>
            <add switchValue="All" name="General">
                <listeners>
                    <add name="Rolling Flat File Trace Listener" />
                </listeners>
            </add>
            <add switchValue="All" name="Thread Log" />
        </categorySources>
        <specialSources>
            <allEvents switchValue="All" name="All Events">
                <listeners>
                    <add name="Rolling Flat File Trace Listener" />
                </listeners>
            </allEvents>
            <notProcessed switchValue="All" name="Unprocessed Category">
                <listeners>
                    <add name="Rolling Flat File Trace Listener" />
                </listeners>
            </notProcessed>
            <errors switchValue="All" name="Logging Errors & Warnings">
                <listeners>
                    <add name="Rolling Flat File Trace Listener" />
                </listeners>
            </errors>
        </specialSources>
    </loggingConfiguration>
</configuration>


In my code, I add a second rolling flat file trace listener using the following:

C#
string logFile = @"C:\TestEnterpriseLogging\TestRollingFile.log";

var builder = new ConfigurationSourceBuilder();
var configSource = new DictionaryConfigurationSource();

    builder.ConfigureLogging().WithOptions
        .DoNotRevertImpersonation()
        .LogToCategoryNamed("New Log Category")
            .WithOptions
            .SendTo.RollingFile("Second Rolling Flat File Trace Listener")
            .ToFile(logFile)
            .WithHeader("======================================================")
            .WithFooter("======================================================")
            .FormatWithSharedFormatter("Text Formatter")
            .UseTimeStampPattern("yyyy-MM-dd HH-mm-ss")
            .RollEvery(RollInterval.Day)
            .RollAfterSize(40000)
            .CleanUpArchivedFilesWhenMoreThan(3)
            .WhenRollFileExists(RollFileExistsBehavior.Overwrite);
            
builder.UpdateConfigurationWithReplace(configSource);

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

// Create a configurator to use to configure our fluent config.
var configurator = new UnityContainerConfigurator(container);
EnterpriseLibraryContainer.ConfigureContainer(configurator, configSource);

// Create a configurator to use to configure our fluent config.
EnterpriseLibraryContainer.Current = new UnityServiceLocator(container);


Finally, I log a test message to the general MyDefaultRolling.log file using this code:

C#
LogEntry logEntry = new LogEntry();
logEntry.Message = "Test logging entry";
logEntry.Categories.Clear();
logEntry.Categories.Add("General");

LogWriter logger = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();
logger.Write(logEntry);


and log a test message to the TestRollingFile.log file using this code:

C#
LogEntry logEntry = new LogEntry();
logEntry.Message = "Test second logging entry";
logEntry.Categories.Clear();
logEntry.Categories.Add("New Log Category");
                                
LogWriter logger = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();
logger.Write(logEntry);


My problem occurs when trying to log messages to a file after adding the new trace listener. The new messages get logged to the new file but any messages sent to the existing file do not appear...almost as if adding a new trace listener has wiped out any existing trace listener entries.

I would be grateful if someone could cast their eye over my code and let me know if I have missed something out or not coded something correctly.

Many thanks.
Posted

1 solution

XML
Well, with a bit more diligence on my part I've solved the issue!  All I had to do was to get a new LogWriter instance each time I added a new listener and make sure I used the appropriate object when logging so I moved the following code from just before calling the Write method to after the fluent configuration API code (making the LogWriter object a class member):

<pre lang="c#">
m_Logger = EnterpriseLibraryContainer.Current.GetInstance<logwriter>();
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900