你能批评一下下面的记录器类吗?可以在多线程网络环境中使用吗?如果没有,我该如何改进它?WriteToLog 方法中的锁定或 FlushLog 方法中的多线程有什么问题吗?
public class Logger
{
private static Logger instance;
private static Queue<LogData> logQueue;
private static string logDir = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["LogDirectory"]);
private static string logFile = "log.txt";
private static int maxLogAge = Int32.Parse(ConfigurationManager.AppSettings["LogMaxAge"]);
private static int queueSize = Int32.Parse(ConfigurationManager.AppSettings["LogQueueSize"]);
private static DateTime LastFlushed = DateTime.Now;
private Logger() { }
public static Logger Instance
{
get
{
if (instance == null)
{
instance = new Logger();
logQueue = new Queue<LogData>();
}
return instance;
}
}
public void WriteToLog(string message)
{
lock (logQueue)
{
LogData logEntry = new LogData(message);
logQueue.Enqueue(logEntry);
if (logQueue.Count >= queueSize || DoPeriodicFlush())
{
FlushLog();
}
}
}
private bool DoPeriodicFlush()
{
TimeSpan logAge = DateTime.Now - LastFlushed;
if (logAge.TotalSeconds >= maxLogAge)
{
LastFlushed = DateTime.Now;
return true;
}
else
{
return false;
}
}
private void FlushLog()
{
System.Threading.ThreadPool.QueueUserWorkItem(q => {
while (logQueue.Count > 0)
{
LogData entry = logQueue.Dequeue();
string logPath = logDir + entry.LogDate + "_" + logFile;
using (System.IO.StreamWriter file = new System.IO.StreamWriter(logPath, true, System.Text.Encoding.UTF8))
{
file.WriteLine(string.Format("{0}\t{1}", entry.LogTime, entry.Message));
}
}
});
}
~Logger()
{
FlushLog();
}
}
public class LogData
{
public string Message { get; set; }
public string LogTime { get; set; }
public string LogDate { get; set; }
public LogData(string message)
{
Message = message;
LogDate = DateTime.Now.ToString("yyyy-MM-dd");
LogTime = DateTime.Now.ToString("HH:mm:ss.fff tt");
}
}
提前致谢,