C#开发高性能Log Help 类设计开发
概述
项目中要在操作数据库的异常处理中加入写Log日志,对于商业上有要求,写log时对其它操作尽可能影响小,不能因为加入log导致耗时太多.
设计思想
在写入日志时利用Queue来管理,写日志有一个专门的backgroud线程来处理,如果没有日志要写,这个线程处于wait状态,这就有了线程的异步处理.
简单的实现方式
//<summary>
//Write Log
//<summary>
public static void WriteLog(string logFile, string msg)
{
try
{
System.IO.StreamWriter sw = System.IO.File.AppendText(
logPath + LogFilePrefix +" "+ logFile + " " +
DateTime.Now.ToString("yyyyMMdd") + ".Log"
);
sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss: ") + msg);
sw.Close();
}
catch (Exception)
{
throw;
}
}
我们的设计图
而后我们在AddLogMessage时semaphore.Release()就能唤醒wait中的log 线程.
代码设计
/// <summary>
/// Log Help class
/// </summary>
/// <remarks>High performance log class</remarks>
public class Log : IDisposable
{
//Log Message queue
private static Queue<LogMessage> _logMessages;
//log save directory
private static string _logDirectory;
//log write file state
private static bool _state;
//log type
private static LogType _logType;
//log life time sign
private static DateTime _timeSign;
//log file stream writer
private static StreamWriter _writer;
/// <summary>
/// Wait enqueue wirte log message semaphore will release
/// </summary>
private Semaphore _semaphore;
/// <summary>
/// Single instance
/// </summary>
private static Log _log;
/// <summary>
/// Gets a single instance
/// </summary>
public static Log LogInstance
{
get { return _log ?? (_log = new Log()); }
}
/// <summary>
/// Initialize Log instance
/// </summary>
private void Initialize()
{
if (_logMessages == null)
{ _state = true;
string logPath = System.Configuration.ConfigurationManager.AppSettings["LogDirectory"];
_logDirectory = string.IsNullOrEmpty(logPath) ? ".\\log\\" : logPath;
if (!Directory.Exists(_logDirectory)) Directory.CreateDirectory(_logDirectory);
_logType = LogType.Daily;
_semaphore = new Semaphore(0, int.MaxValue, Constants.LogSemaphoreName);
_logMessages = new Queue<LogMessage>();
var thread = new Thread(Work) {IsBackground = true};
thread.Start();
}
}
/// <summary>
/// Create a log instance
/// </summary>
private Log()
{
Initialize();
}
/// <summary>
/// Log save name type,default is daily
/// </summary>
public LogType LogType
{
get { return _logType; }
set { _logType = value; }
}
/// <summary>
/// Write Log file work method
/// </summary>
private void Work()
{
while (true)
{
//Determine log queue have record need wirte
if (_logMessages.Count > 0)
{
FileWriteMessage();
}
else
if (WaitLogMessage()) break;
}
}
/// <summary>
/// Write message to log file
/// </summary>
private void FileWriteMessage()
{
LogMessage logMessage;
lock (_logMessages)
{
logMessage = _logMessages.Dequeue();
}
if (logMessage != null)
{
FileWrite(logMessage);
}
}
/// <summary>
/// The thread wait a log message
/// </summary>
补充:软件开发 , C# ,