009_.Net 向服务器系统写程序错误日志和向系统管理员发送错误邮件!
1.向服务器系统写日志:
1)动作按钮
protected void btnCal_Click(object sender, System.EventArgs e)
{
try
{
int nInput = int.Parse(tbInput.Text);
long nResult=1;
for(int i=1;i<=nInput;i++)
checked{nResult *= i;}
lbResult.Text = nResult.ToString();
}
catch(OverflowException)//溢出错误异常处理
{
throw new Exception("输入的数字太大,我受不了了!");
}
catch(FormatException)//输入字符格式错误异常处理
{
Response.Write("嘿!要输入整数!");
}
catch(Exception ee)
{
Response.Write("发生错误,信息为:"+ee.Message);
}
}
2)Page_Error
protected void WebForm1_Error(object sender, System.EventArgs e)
{
string strMessage = Server.GetLastError().Message;
//Response.Write(strMessage);
Server.ClearError();
//以下把信息写入windows日志
//要把aspnet用户添加到管理员组中,以便有写注册表权限
if(!EventLog.SourceExists("mySource"))
EventLog.CreateEventSource("mySource","myLog");
EventLog Event = new EventLog();
Event.Source = "mySource";
Event.WriteEntry(strMessage,EventLogEntryType.Warning);
//EventLog.Delete("myLog");
throw new Exception("我处理不了,请最高人民法院处理!");
}
2.由程序级Error处理程序来处理错误:向管理员发邮件:
3)向管理员发邮件
protected void Application_Error(Object sender, EventArgs e)
{
//把错误信息发送到作者
string strPageUrl = Request.Path;
Exception ErrorInfo =Server.GetLastError();
//Server.ClearError();
string strMessage = "Url:" + strPageUrl + "</br>";
strMessage = strMessage + " Error: ";
strMessage = strMessage + ErrorInfo.ToString() + "</br>";
MailMessage Mymessage = new MailMessage();
Mymessage.To = "shaoxufeng@fujitec.com.cn";
Mymessage.From = "shaoxufeng@fujitec.com.cn";
Mymessage.Subject = "ASP.NET Error";
Mymessage.BodyFormat = MailFormat.Text;
Mymessage.Body = strMessage;
Mymessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); //basic authentication
Mymessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "shaoxufeng");//set your username here
Mymessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "shaoxufeng3600"); //set your password here
// SmtpMail.SmtpServer="lsg.moon.net";
SmtpMail.SmtpServer = "mail.fujitec.com.cn";
SmtpMail.Send(Mymessage);
}