1. 程式人生 > >C# 異常日誌記錄

C# 異常日誌記錄

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace HanXingExam.Common
{
public class ErrorLog
{
public static void WriteLog(Exception ex)
{
string errorTime = "異常時間:" + DateTime.Now.ToString();
string errorAddress = "異常地址:" + HttpContext.Current.Request.Url.ToString();
string errorInfo = "異常資訊:" + ex.Message;
string errorSource = "錯誤源:" + ex.Source;
string errorType = "執行型別:" + ex.GetType();
string errorFunction = "異常函式:" + ex.TargetSite;
string errorTrace = "堆疊資訊:" + ex.StackTrace;
HttpContext.Current.Server.ClearError();
System.IO.StreamWriter writer = null;
try
{


//寫入日誌
string path = string.Empty;
path = HttpContext.Current.Server.MapPath("~/ErrorLogs/");
//不存在則建立錯誤日誌資料夾
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
path += string.Format(@"\{0}.txt", DateTime.Now.ToString("yyyy-MM-dd"));

writer = !System.IO.File.Exists(path) ? System.IO.File.CreateText(path) : System.IO.File.AppendText(path); //判斷檔案是否存在,如果不存在則建立,存在則新增
writer.WriteLine("使用者IP:" + HttpContext.Current.Request.UserHostAddress);
writer.WriteLine(errorTime);
writer.WriteLine(errorAddress);
writer.WriteLine(errorInfo);
writer.WriteLine(errorSource);
writer.WriteLine(errorType);
writer.WriteLine(errorFunction);
writer.WriteLine(errorTrace);
writer.WriteLine("********************************************************************************************");
}
finally
{
if (writer != null)
{
writer.Close();
}
}
}
}
}