Rolling flat file issue

Topics: Logging Application Block
Jul 19, 2010 at 3:06 PM

Hi All,

I am using a rolling flat file for logging. But the Text formatter i have used is not appearing to work. I have updated my Text Formatter to log only 'Message' and 'Timestamp'. If i use a flat file trace listener instead of rolling flat file, i  am getting the desired results. but when i am using rolling flat file trace listener, all other details are also getting logged. can anyone pls help?? I need to log only the 'Message' and 'Timestamp'

Jul 20, 2010 at 1:15 AM

Are you sure? Could you post the relevant sections of your config file?

Sarah Urmeneta
Global Technology and Solutions
Avanade, Inc.
entlib.support@avanade.com

Jul 20, 2010 at 6:19 AM

Yes, My Rolling flat file is in a different project since it is reused. here is my RollingFlatFileTraceListener.cs

using System;
using System.Configuration;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using System.IO;
using System.Diagnostics;
using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder;
using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging.Formatters;
using Microsoft.Practices.EnterpriseLibrary.Logging;

namespace EnterpriseLibrary.Logging.Extensions
{
    /// <summary>
    /// RollingFlatFileTraceListener is an example of an extension of the CustomTraceListener in
    /// the Logging Application Block 2.0.  The purpose of this example is to demonstrate the robust
    /// extensibility of the Logging Application block in the Enterprise Library 2.0 frameworks.
    /// This code has not been battle tested and is not recommended (without testing) for production use.
    /// </summary>
    ///

    [ConfigurationElementType(typeof(CustomTraceListenerData))]
    public class RollingFlatFileTraceListener: CustomTraceListener
    {
        private static string  logFileNamePart;

        public static string LogFileNamePart
        {
            get { return logFileNamePart; }
            set { logFileNamePart = value; }
        }
       
        public RollingFlatFileTraceListener()
            : base()
        { }

        /// <summary>
        /// Override of Write.  Gets the "fileName" attribute and calls WriteToFile
        /// </summary>
        /// <param name="message"></param>
        public override void Write(string message)
        {
            StringDictionary ourAttributes = base.Attributes;
            WriteToFile(RootAndFormatFileName(ourAttributes["fileName"]), message);
        }
        /// <summary>
        /// Override of WriteLine -> calls Write()
        /// </summary>
        /// <param name="message"></param>
        public override void WriteLine(string message)
        {
            this.Write(message);
        }

        /// <summary>
        /// Entry point override of TraceData  -> calls Write()
        /// </summary>
        /// <param name="eventCache"></param>
        /// <param name="source"></param>
        /// <param name="eventType"></param>
        /// <param name="id"></param>
        /// <param name="data"></param>
        public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data)
        {
            this.Write(data.ToString());
      
        }

        /// <summary>
        /// Private method to write string to file
        /// </summary>
        /// <param name="fileName">name of file</param>
        /// <param name="message">message to write to file</param>
        private void WriteToFile(string fileName, string message)
        {

            FileStream objFS = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
            StreamWriter sw = new StreamWriter(objFS);
            sw.WriteLine(Environment.NewLine + message);
            sw.BaseStream.Seek(0, SeekOrigin.End);
            sw.Flush();
            sw.Close();       
        }

        /// <summary>
        /// Private method to format the filename
        /// </summary>
        /// <param name="fileName">filename</param>
        /// <returns>string name of formatted file</returns>
        private string RootAndFormatFileName(string fileName)
        {
           
            string rootedFileName = fileName;
            const string DATETOKEN = "{Date}";
            const string DATETOKEN_YYYY_MMM = "{Date_YYYY_MM}";
            const string REGION = "{Region}";

            if (!Path.IsPathRooted(rootedFileName))
            {
                rootedFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, rootedFileName);
            }

            DateTime lastDate = DateTime.Today;
            string datePortion = string.Empty;
            if (fileName.Contains(DATETOKEN))
            {
                datePortion = string.Format("{0:0000}{1:00}{2:00}", lastDate.Year, lastDate.Month, lastDate.Day);
                rootedFileName = rootedFileName.Replace(DATETOKEN, datePortion);
            }
            if (fileName.Contains(DATETOKEN_YYYY_MMM))
            {
                datePortion = string.Format("{0:0000}{1:00}", lastDate.Year, lastDate.Month);
                rootedFileName = rootedFileName.Replace(DATETOKEN_YYYY_MMM, datePortion);
            }

            if (logFileNamePart !=null || logFileNamePart !=string.Empty )
            {
                rootedFileName = rootedFileName.Replace(REGION, logFileNamePart);
            }

           

            string directory = Path.GetDirectoryName(rootedFileName);

            if (directory.Length != 0 && !Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }

            return rootedFileName;
        }

    }

}

 

 

 

and here is my app.config file from the project from where i am referring the above file,

 

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    <section name="exceptionHandling" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration.ExceptionHandlingSettings, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
  </configSections>
  <loggingConfiguration name="Logging Application Block" tracingEnabled="true"
    defaultCategory="" logWarningsWhenNoCategoriesMatch="true">
    <listeners>
      <add fileName="Logs\TestLog_ {Date}.log" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.CustomTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        traceOutputOptions="None" filter="All" type="EnterpriseLibrary.Logging.Extensions.RollingFlatFileTraceListener, EnterpriseLibrary.Logging.Extensions, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
        name="Custom Trace Listener" initializeData="" formatter="Text Formatter" />
      <add source="TEST" formatter="Text Formatter" log="TEST" machineName=""
        listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        traceOutputOptions="None" filter="Error" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        name="Formatted EventLog TraceListener" />
    </listeners>
    <formatters>
    <add template="Timestamp: {timestamp}&#xD;&#xA;Message: {message}"
        type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        name="Text Formatter" />
    </formatters>
    <categorySources>
      <add switchValue="Error" name="ERROR">
        <listeners>
          <add name="Formatted EventLog TraceListener" />
        </listeners>
      </add>
      <add switchValue="All" name="LOG">
        <listeners>
          <add name="Custom 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">
      </errors>
    </specialSources>
  </loggingConfiguration>
  <exceptionHandling>
    <exceptionPolicies>
      <add name="Jobs Policy">
        <exceptionTypes>
          <add type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
            postHandlingAction="None" name="Exception">
            <exceptionHandlers>
              <add logCategory="ERROR" eventId="100" severity="Error"
                title="Enterprise Library Exception Handling" formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                priority="0" useDefaultLogger="false" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                name="Logging Handler" />
            </exceptionHandlers>
          </add>
        </exceptionTypes>
      </add>
    </exceptionPolicies>
  </exceptionHandling>

</configuration>

notice that my Text Formatter contains only Message and Timestamp,

<add template="Timestamp: {timestamp}&#xD;&#xA;Message: {message}"

Jul 20, 2010 at 8:40 AM

When writing the actual message, you should use this.Formatter.Format(logEntry).  Therefore, in your TraceData method, check if the data parameter is an instance of a LogEntry, if it is, call

this.Write(this.Formatter.Format(data as LogEntry));  

If the data parameter is simply a string, you can convert it first to a LogEntry object.

 

Sarah Urmeneta
Global Technology and Solutions
Avanade, Inc.
entlib.support@avanade.com

Jul 20, 2010 at 9:54 AM

Thanks for your reply!

Will try this out.