Labels

Wednesday, June 20, 2007

Thread - Wait & Set - Logger

public class Logger

{

private ArrayList loggerThreadList; // Buffer used by the consumer logger thread

private ArrayList logList;  // Buffer used by the producers to store the log messages

private string logFilePath;

 

private static Logger logger = new Logger();

private EventWaitHandle wh = new AutoResetEvent(false);

 

 

private Logger()

{

            loggerThreadList = new ArrayList();

            logList = new ArrayList();

            logFilePath = "LogFiles/Log.txt";

 

            OpenLoggerFileStream();

            CreateThread();

}

 

private void CreateThread()

        {

           Thread thrd = new Thread(new ThreadStart(LoggerRun));

           thrd.Name = “Logger Thread”;

           thrd.Priority = ThreadPriority.BelowNormal;

           try

           {

               thrd.Start();

           }

           catch (Exception exp)

           {

               // TODO: What to do if this exception occurs?

           }

        }

 

private void LoggerRun()

           {

               LogData logData;

               // Loop till the application is alive

               while (!ApplicationEnd)

               {

                   int loggerListCount = 0;

                   lock (loggerThreadList.SyncRoot)

                   {

                       loggerListCount = loggerThreadList.Count;

                   }

                   // Log the messages until the buffer is not empty

                   while (loggerListCount > 0)

                   {

                       lock(loggerThreadList.SyncRoot)

                            logData = loggerThreadList[0] as LogData;

                       // Write the message to the file

                       PostLog(logData);

                       lock(loggerThreadList.SyncRoot)

                            // Remove the message from the buffer

                            loggerThreadList.RemoveAt(0);

                       loggerListCount--;

                   }

                  

                   wh.WaitOne();  // Wait till the new log message buffer is full

              }

 

            // Application End Event has fired, close the thread

            CleanUp();

       }

 

 

private void AddMessageToBuffer(LogData logData)

        {

            if (!ApplicationEnd)

            {

                lock (logList.SyncRoot)

                {

                    logList.Add(logData);  // Keeps on adding until the count reaches threashhold

                    if (logList.Count >= BufferSizeThreshold)

                    {

                        lock (loggerThreadList.SyncRoot)

                        {

                            loggerThreadList.AddRange(logList.GetRange(0, logList.Count));  // Adding all the elements in one shot.

                        }

                        logList.RemoveRange(0, logList.Count);

                        wh.Set();  // Waiking up the thread

                    }

                }

            }

        }

 

private void OpenLoggerFileStream()

     {

           try

           {

               FileStream stream;

 

               if (!File.Exists(logFilePath))

                   stream = File.Create(logFilePath);

               else

                   stream = new FileStream(logFilePath, FileMode.Append, FileAccess.Write);

              

               streamWriter = new StreamWriter(stream);

           }

           catch (Exception ex)

           {

               // This exception can occur when there is no access to the log folder.

           }

  }

 

 

private void PostLog(LogData logData)

        {

            StringBuilder logEntry = new StringBuilder(6);

            logEntry = logEntry.Append(“….”);

 

           try

           {

               long fileSizeInKB = streamWriter.BaseStream.Length / 1024;

 

               // Write to the log file

               if (fileSizeInKB < MaximumLogFileSize)

               {

                   streamWriter.Write(logEntry.ToString());

                   streamWriter.Flush();

               }

               else

               {

                   // Log file size has exceeded the maximum allowed file size

                   try

                   {

                       // Close the old file

                       streamWriter.BaseStream.Flush();

                       streamWriter.BaseStream.Close();

                   }

                   catch (Exception ex)

                   {

                       // Ignore these exceptions

                   }

 

                   try

                   {

                       // Archive the old file

                       File.Move(logFilePath, logFilePath.Substring(0, logFilePath.Length - 4) + DateTime.Now.ToBinary() + ".txt");

                       // Open a new file

                       OpenLoggerFileStream();

                       streamWriter.Write(logEntry.ToString());

                   }

                   catch (Exception e)

                   {

                       // Ignore the exception

                   }

               }

           }

           catch (Exception ex)

           {

               // Could not write to the file

               // TODO: This error should be logged to the Windows Event Log?

           }

 }

}

 

Thanks & Regards,

Arun Manglick

SMTS || Microsoft Technology Practice || Bridgestone - Tyre Link || Persistent Systems || 3023-6258

 

DISCLAIMER ========== This e-mail may contain privileged and confidential information which is the property of Persistent Systems Pvt. Ltd. It is intended only for the use of the individual or entity to which it is addressed. If you are not the intended recipient, you are not authorized to read, retain, copy, print, distribute or use this message. If you have received this communication in error, please notify the sender and delete all copies of this message. Persistent Systems Pvt. Ltd. does not accept any liability for virus infected mails.

No comments:

Post a Comment