using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; namespace CustomXmlConfiguration.Logger { /// <summary> /// A Logging class implementing the Singleton pattern and an internal Queue to be flushed perdiodically /// </summary> public class LogWriter { private static LogWriter instance; private static Queue<Log> logQueue; private static string logDir = LogConfiguration.DirectoryName; private static string logFile = LogConfiguration.LogFileName; private static int maxLogAge = LogConfiguration.MaxLogAge; private static int queueSize = LogConfiguration.QueueSize; private static DateTime LastFlushed = DateTime.Now; /// <summary> /// Private constructor to prevent instance creation /// </summary> private LogWriter() { } /// <summary> /// An LogWriter instance that exposes a single instance /// </summary> public static LogWriter Instance { get { // If the instance is null then create one and init the Queue if (instance == null) { instance = new LogWriter(); logQueue = new Queue<Log>(); } return instance; } } /// <summary> /// The single instance method that writes to the log file /// </summary> /// <param name="message">The message to write to the log</param> public void WriteToLog(string message) { // Lock the queue while writing to prevent contention for the log file lock (logQueue) { // Create the entry and push to the Queue Log logEntry = new Log(message); logQueue.Enqueue(logEntry); // If we have reached the Queue Size then flush the Queue if (logQueue.Count >= queueSize || DoPeriodicFlush()) { FlushLog(); } } } /// <summary> /// /// </summary> /// <returns></returns> private bool DoPeriodicFlush() { TimeSpan logAge = DateTime.Now - LastFlushed; if (logAge.TotalSeconds >= maxLogAge) { LastFlushed = DateTime.Now; return true; } else { return false; } } /// <summary> /// Flushes the Queue to the physical log file /// </summary> private void FlushLog() { while (logQueue.Count > 0) { Log entry = logQueue.Dequeue(); string logPath = string.Format("{0}{1}_{2}",logDir,entry.LogDate,logFile); // This could be optimised to prevent opening and closing the file for each write using (FileStream fs = File.Open(logPath, FileMode.Append, FileAccess.Write)) { using (StreamWriter log = new StreamWriter(fs)) { log.WriteLine(string.Format("{0}\t{1}\n\n",entry.LogTime,entry.Message)); } } } } } }
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)