背景
ELMAH就是一個日志的攔截和處理組件,說到.net的日志組件,大家的第一反應該是Log4Net、NLog等這些東西,關于Log4Net和NLog,可以說是.net日志組件里面使用最為廣泛的組件了,它們功能強大、使用方便,
優點
相比它們:
1、ELMAH的使用更加簡單,它甚至不用寫一句代碼;
2、ELMAH是一種“可拔插式”的組件,即在一個運行的專案里面我們可以隨意輕松加入日志功能,或者移除日志功能;
3、ELMAH組件自帶界面,不用寫任何代碼,即可查看例外日志的界面;
4、組件提供了一個用于集中記錄和通知錯誤日志的機制,通過郵件的機制通知錯誤資訊給相關人員,
代碼實作
1、nuget安裝 using Elmah;

2、Application_Error 例外404處理
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; } }
3、排除 Elmah 404 寄信通知
public void ErrorMail_Filtering(object sender, ExceptionFilterEventArgs e) { if (e.Exception is HttpException httpException && (httpException.GetHttpCode() == 404 || httpException.Message.StartsWith(_exceptionMsg))) { e.Dismiss(); } }
4、自定 Elmah 發信主旨
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; }
5、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對于中小專案來說不失為一種不錯的選擇;
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/248362.html
標籤:.NET技术
