該檔案可以在系統發生某些事件的時候被執行
個人用到的是捕捉例外的功能
在此做個筆記
<%@ Application Language="C#" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Security" %>
<script RunAt="server">
void Application_Start(object sender, EventArgs e)
{
// 應用程式啟動時執行的程式碼
}
void Application_End(object sender, EventArgs e)
{
// 應用程式關閉時執行的程式碼
}
void Application_Error(object sender, EventArgs e)
{
// 發生未處理錯誤時執行的程式碼
HttpServerUtility server = HttpContext.Current.Server;
HttpRequest request = HttpContext.Current.Request;
HttpSessionState session = HttpContext.Current.Session;
HttpBrowserCapabilities brower = HttpContext.Current.Request.Browser;
Exception ex = server.GetLastError();
System.Net.IPAddress ServerIP = new System.Net.IPAddress(System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName()).AddressList[0].Address);
StreamWriter sw = null;
try
{
if (ex.InnerException != null)
{
ex = ex.InnerException;
}
string filePath = string.Format(@"{0}Log\err_log_" + DateTime.Now.ToString("yyyyMMdd") + ".txt", server.MapPath("~/"));
sw = File.Exists(filePath) ? new StreamWriter(filePath, true) : File.CreateText(filePath);
sw.WriteLine("----------Strat----------");
sw.WriteLine("----------[目前時間:" + DateTime.Now.ToString() + "]----------");
sw.WriteLine("事件發生網頁網址:" + request.Url);
sw.WriteLine("事件發生路徑:" + request.Path);
sw.WriteLine("例外狀況訊息:" + ex.Message);
//事件發生網頁網址
sw.WriteLine("例外堆疊:" + ex.StackTrace);
sw.WriteLine("造成錯誤的程式名稱:" + ex.Source);
//使用者名稱
if (session != null)
sw.WriteLine("使用者名稱:" + Session["UserID"].ToString());
sw.WriteLine("識別系統別:" + request.UserHostAddress);
sw.WriteLine("IP:" + ServerIP.ToString());
sw.WriteLine("使用瀏覽器:" + brower.Type);
sw.WriteLine("是否支援Cookie:" + (brower.Cookies ? "是" : "否"));
sw.WriteLine("伺服器名稱:" + request.ServerVariables["SERVER_NAME"]);
sw.WriteLine("----------END----------");
}
catch (HttpException HE)
{
throw HE;
}
catch (ArgumentNullException ANE)
{
throw ANE;
}
catch (ArgumentException AE)
{
throw AE;
}
catch (UnauthorizedAccessException UAE)
{
throw UAE;
}
catch (DirectoryNotFoundException DNFE)
{
throw DNFE;
}
catch (IOException IOE)
{
throw IOE;
}
catch (SecurityException SE)
{
throw SE;
}
finally
{
sw.Close();
sw.Dispose();
}
}
</script>
Application_Error可以捕捉網站中的例外
但是如果該例外在網頁中就已經被捕捉
就不會被Application_Error給catch到
所以簡單說Application_Error專門接漏網之魚
這很適合用在你在本機執行沒問題
丟到IIS莫名其妙掛掉的情況
還有一些例外情況但被忽略掉的情形
上面範例就是當發生例外時
會取得該例外物件
然後描述該例外的情形
最好用的就是HttpContext.Current.Request的Url跟Path屬性
他可以指出當前的Request是來自於哪個網址跟路徑
這在IIS上執行有bug時又不曉得bug從何而來很好用
其餘的HttpContext.Current.Server、HttpContext.Current.Session、HttpContext.Current.Request.Browser
都可以讓你取得當下相關資訊並且在Application_Error寫入txt或是資料庫
方便你事後分析問題點
參考文獻
[1] http://www.dotblogs.com.tw/mis2000lab/archive/2008/04/28/3526.aspx
[2] http://sharebody.com/list.asp?id=50684
[3] http://msdn.microsoft.com/zh-tw/library/vstudio/2027ewzw%28v=vs.100%29.aspx
[4] http://www.webjx.com/htmldata/2006-08-14/1155516831.html
[5] http://myprogramlog.blogspot.tw/2013/09/globalasax-applicationbeginrequest.html
沒有留言:
張貼留言