ELMAH就是一個日誌的攔截和處理組件,說到.net的日誌組件,你們的第一反應該是Log4Net、NLog等這些東西,關於Log4Net和NLog,能夠說是.net日誌組件裏面使用最爲普遍的組件了,它們功能強大、使用方便。web
相比它們:編輯器
一、ELMAH的使用更加簡單,它甚至不用寫一句代碼;google
二、ELMAH是一種「可拔插式」的組件,即在一個運行的項目裏面咱們能夠隨意輕鬆加入日誌功能,或者移除日誌功能;spa
三、ELMAH組件自帶界面,不用寫任何代碼,便可查看異常日誌的界面;.net
四、組件提供了一個用於集中記錄和通知錯誤日誌的機制,經過郵件的機制通知錯誤信息給相關人員。3d
一、nuget安裝 using Elmah;日誌
二、Application_Error 異常404處理code
protected void Application_Error(object sender, EventArgs e) { if (BQoolCommon.Helpers.Setting.CommonSetting.IsProd()) { if (e is ExceptionFilterEventArgs exceptionFilter) { if (exceptionFilter.Exception is HttpException httpException && httpException.Message.StartsWith(_exceptionMsg)) { Response.Redirect("/"); } } Response.Clear(); Server.ClearError(); Response.StatusCode = 404; } }
三、排除 Elmah 404 寄信通知orm
public void ErrorMail_Filtering(object sender, ExceptionFilterEventArgs e) { if (e.Exception is HttpException httpException && (httpException.GetHttpCode() == 404 || httpException.Message.StartsWith(_exceptionMsg))) { e.Dismiss(); } }
四、自定 Elmah 發信主旨server
void ErrorMail_Mailing(object sender, Elmah.ErrorMailEventArgs e) { string machineName = "none server"; try { if (Request != null) { machineName = Request.ServerVariables["HTTP_HOST"]; } } catch { } // 取得 Elamh ErrorMail 的主旨 // "$MachineName$ at $ErrorTime$ : {0}" string elmahSubject = e.Mail.Subject; //替換 ErrorMail 的主旨內容 string emailSubject = string.Format("BigCRM.Web Error => {0}", elmahSubject .Replace("$MachineName$", machineName) ); e.Mail.Subject = emailSubject; }
五、web.config配置
<elmah> <!-- See http://code.google.com/p/elmah/wiki/SecuringErrorLogPages for more information on remote access and securing ELMAH. --> <security allowRemoteAccess="false"/> </elmah> <location path="elmah.axd" inheritInChildApplications="false"> <system.web> <httpHandlers> <add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah"/> </httpHandlers> <!-- See http://code.google.com/p/elmah/wiki/SecuringErrorLogPages for more information on using ASP.NET authorization securing ELMAH. <authorization> <allow roles="admin" /> <deny users="*" /> </authorization> --> </system.web> <system.webServer> <handlers> <add name="ELMAH" verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" preCondition="integratedMode"/> </handlers> </system.webServer> </location>
ELMAH對於中小項目來講不失爲一種不錯的選擇;