public static class LogWriter
{
private static ReaderWriterLockSlim writeLock = new ReaderWriterLockSlim();
public static void WriteExceptionLog(string content)
{
#if DEBUG
MessageBox.Show(content);
#endif
WriteLog(content, Constant.EXCEPTION_LOG_PATH);
}
public static void WriteLog(string content, string path)
{
try
{
writeLock.EnterWriteLock();
string directory = Path.GetDirectoryName(path);
if (!Directory.Exists(Path.GetDirectoryName(directory)))
Directory.CreateDirectory(directory);
using (StreamWriter writeFile = new StreamWriter(path, true))
{
content = DateTime.Now + " : " + content;
writeFile.WriteLine(content);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
writeLock.ExitWriteLock();
}
}
}
我有寫日誌的類。因爲我正在異步寫入日誌,所以我需要放置一個鎖並在寫入完成時釋放它,但這似乎是一種笨重的解決方案,甚至可能導致性能不佳。更好的辦法來處理異步日誌寫入
什麼是更好的方式來處理呢?
有沒有原因不使用現有的日誌庫,如'NLog'或'log4Net'? – RePierre