2010年7月16日 星期五

如何將錯誤訊息寫到LOG檔中

static Mutex mu = new Mutex(false);

private void MyMethod
{
try
{
.....
}
catch (Exception ex)
{
Trace.WriteLine(ex.ToString());
mu.WaitOne();
WriteErrorLog(ex);
mu.ReleaseMutex();
}
}



private void WriteErrorLog(Exception ex)
{

StreamWriter streamWriter;

string strFileName, strMessage;
strFileName = "ErrorLog-" + DateTime.Now.ToString("yyyyMMdd") + ".LOG";

strMessage = "====================\r\n" + DateTime.Now.ToString ("yyyy/MM/dd HH:mm:ss") + "\r\n====================\r\n" + ex.ToString() + "\r\n\r\n";

string path = Application.StartupPath + "\\LOG\\"+ strFileName;
// Delete the file if it exists.
if (!File.Exists(path))
{
File.Create(path);
}
streamWriter= File.AppendText(path);
streamWriter.WriteLine(strMessage);
streamWriter.Flush();
streamWriter.Close();
streamWriter.Dispose();
MessageBox.Show("Net Matrix系統發生錯誤,即將關閉,請洽系統管理員 \r\n\r\n錯誤訊息:\r\n\r\n " + strMessage, "警告");

}

PS:若使用File.AppendAllText()有時會發生IOException,目前尚未解決

沒有留言:

張貼留言