#region 将错误以文本的形式记录下来.
/// <summary>
/// 将错误以文本的形式记录下来.
/// </summary>
/// <param name="Ex">捕获的异常.</param>
public static void WriteLog(Exception Ex)
{
string ErrTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
string ErrSource = Ex.Source;
string ErrTargetSite = Ex.TargetSite.ToString();
string ErrMsg = Ex.Message;
string ErrStackTrace = Ex.StackTrace;
string FilePath = System.Web.HttpContext.Current.Server.MapPath("~/ErrorLog/");
if (!Directory.Exists(FilePath))
{
Directory.CreateDirectory(FilePath);
}
string FileName = FilePath + DateTime.Now.ToString("yyyy-MM-dd") + ".log";
if (GetFileSize(FileName) > 1024 * 3)
{
CopyToBak(FileName);
}
StreamWriter MySw = new StreamWriter(FileName, true);
MySw.WriteLine("\r\n*************************************************Error*Report*Start*************************************************\r\n");
MySw.WriteLine("错误时间 : " + ErrTime);
MySw.WriteLine("错误对象 : " + ErrSource);
MySw.WriteLine("异常方法 : " + ErrTargetSite);
MySw.WriteLine("错误信息 : " + ErrMsg);
MySw.WriteLine("堆栈内容 : ");
MySw.WriteLine(ErrStackTrace);
MySw.WriteLine("\r\n*************************************************Error*Report*End*************************************************\r\n");
MySw.Close();
//MySw.Dispose();
}
#endregion
页面中:
try{}
catch (Exception Ex)
{
ErrorLog.WriteLog(Ex);
}
就能捕获到错误信息.