elmah(英文):https://code.google.com/p/elmah/
寫作思路:先看結果,然后再說原理
elmah文章基本內容如下
1.安裝
2.基本使用
3.詳細配置講解
簡介
ELMAH是一個開源項目,其目的是記錄和報告在asp.net Web應用程序未處理的異常。
早在2004年9月與Atif阿齊茲和斯科特·米切爾發表在MSDN Library,其目的是作為一個概念證明,編寫自包含的功能與ASP.NET HTTP模塊和處理程序是絕對有可能的,大多有這種特征可能是一篇文章插入沒有重新編譯和小的改動配置文件的現有應用程序。 為了展示這些概念的文章發表了示例項目,其目的是為了攔截,記錄和通知ASP.NET應用程序中發生未處理的異常。 它被賦予ELMAH的名稱,錯誤日志記錄模塊和處理程序。
1.安裝
新建一個MVC項目,在nuget的控制臺輸入命令回車進行安裝:Install-Package elmah
MVC項目詳情如下
開發環境
vs 2012
sql server 2012
HomeController:
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;namespace Jean.ElmahSample.Controllers{ public class HomeController : Controller { // // GET: /Home/ public ActionResult Index() { return View(); } }}
Index View :
運行顯示效果:
安裝后 web.config 文件內容變為如下圖-1-1所示(暫時先不要管里面的內容是什么意思,后面再慢慢解答)
圖-1-1
<?xml version="1.0" encoding="utf-8"?><!-- 有關如何配置 ASP.NET 應用程序的詳細信息,請訪問 http://go.microsoft.com/fwlink/?LinkId=152368 --><configuration> <configSections> <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> <sectionGroup name="elmah"> <section name="security" requirePermission="false" type="Elmah.SecuritySectionHandler, Elmah" /> <section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah" /> <section name="errorMail" requirePermission="false" type="Elmah.ErrorMailSectionHandler, Elmah" /> <section name="errorFilter" requirePermission="false" type="Elmah.ErrorFilterSectionHandler, Elmah" /> </sectionGroup> </configSections> <connectionStrings> <add name="DefaultConnection" PRoviderName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)/v11.0;Initial Catalog=aspnet-Jean.ElmahSample-20140524091142;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|/aspnet-Jean.ElmahSample-20140524091142.mdf" /> </connectionStrings> <appSettings> <add key="webpages:Version" value="2.0.0.0" /> <add key="webpages:Enabled" value="false" /> <add key="PreserveLoginUrl" value="true" /> <add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusivejavaScriptEnabled" value="true" /> </appSettings> <system.web> <httpRuntime targetFramework="4.5" /> <compilation debug="true" targetFramework="4.5" /> <authentication mode="Forms"> <forms loginUrl="~/Account/Login" timeout="2880" /> </authentication> <pages> <namespaces> <add namespace="System.Web.Helpers" /> <add namespace="System.Web.Mvc" /> <add namespace="System.Web.Mvc.Ajax" /> <add namespace="System.Web.Mvc.Html" /> <add namespace="System.Web.Optimization" /> <add namespace="System.Web.Routing" /> <add namespace="System.Web.WebPages" /> </namespaces> </pages> <profile defaultProvider="DefaultProfileProvider"> <providers> <add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" /> </providers> </profile> <membership defaultProvider="DefaultMembershipProvider"> <providers> <add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePassWordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" /> </providers> </membership> <roleManager defaultProvider="DefaultRoleProvider"> <providers> <add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" /> </providers> </roleManager> <!-- If you are deploying to a cloud environment that has multiple web server instances, you should change session state mode from "InProc" to "Custom". In addition, change the connection string named "DefaultConnection" to connect to an instance of SQL Server (including SQL Azure and SQL Compact) instead of to SQL Server Express. --> <sessionState mode="InProc" customProvider="DefaultSessionProvider"> <providers> <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" /> </providers> </sessionState> <httpModules> <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" /> <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" /> <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" /> </httpModules> </system.web> <system.webServer> <validation validateIntegratedModeConfiguration="false" /> <handlers> <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" /> <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" /> <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%/Microsoft.NET/Framework/v4.0.30319/aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" /> <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%/Microsoft.NET/Framework64/v4.0.30319/aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" /> <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /> </handlers> <modules> <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" preCondition="managedHandler" /> <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" preCondition="managedHandler" /> <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" preCondition="managedHandler" /> </modules> </system.webServer> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" /> <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-1.3.0.0" newVersion="1.3.0.0" /> </dependentAssembly> </assemblyBinding> </runtime> <entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework"> <parameters> <parameter value="v11.0" /> </parameters> </defaultConnectionFactory> </entityFramework> <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></configuration>
2.基本使用
錯誤數據源(錯誤存儲的地方)
2.1 存儲在內存中
輸入地址 http://localhost:5547/home/about
看下圖結果
圖2-1
輸入地址 http://localhost:5547/elmah.axd (elmah.axd不是一個真實存在的文件,也不需要我們自己去新建)
看下圖結果
圖2-2
點擊并試一試
rss FEED
DOWNLOAD LOG
點擊圖2-2中Details 查看詳情如下
默認情況下,錯誤存儲在內存中,錯誤數量上限為15
修改web.config中elmah節點,并設置錯誤數量上限為5
(當第6個錯誤出現時,前面5個存在的錯誤有一個會被最新的錯誤記錄替換)
<elmah> <!--Storing errors in memory--> <errorLog type="Elmah.MemoryErrorLog, Elmah" size="5" /></elmah>
2.2 存儲在xml中
修改web.config中elmah節點,如下圖
<elmah> <!--Storing errors in XML files--> <errorLog type="Elmah.XmlFileErrorLog, Elmah" logdata-path="~/App_Data" /></elmah>
輸入地址 http://localhost:5547/home/adjkf
看下圖結果
2.3 存儲在sql server中
2.3.1 修改web.config文件,關鍵信息如下
<elmah> <!--Storing errors in SQL Server--> <errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="Elmah.Sql" /></elmah><connectionStrings> <!--Northwind為我測試的數據庫名稱--> <add name="Elmah.Sql" connectionString="Data Source=.;Initial Catalog=Northwind;Trusted_Connection=True" /> </connectionStrings>
2.3.2 在數據庫里執行一下下面sql腳本(我測試的數據庫是Northwind)
執行后會創建一張表ELMAH_Error和3個存儲過程
/* ELMAH - Error Logging Modules and Handlers for ASP.NET Copyright (c) 2004-9 Atif Aziz. All rights reserved. Author(s): Atif Aziz, http://www.raboof.com Phil Haacked, http://haacked.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */-- ELMAH DDL script for Microsoft SQL Server 2000 or later.-- $Id: SQLServer.sql 677 2009-09-29 18:02:39Z azizatif $DECLARE @DBCompatibilityLevel INTDECLARE @DBCompatibilityLevelMajor INTDECLARE @DBCompatibilityLevelMinor INTSELECT @DBCompatibilityLevel = cmptlevelFROM master.dbo.sysdatabasesWHERE name = DB_NAME()IF @DBCompatibilityLevel <> 80 BEGIN SELECT @DBCompatibilityLevelMajor = @DBCompatibilityLevel / 10 , @DBCompatibilityLevelMinor = @DBCompatibilityLevel % 10 PRINT N' =========================================================================== WARNING! --------------------------------------------------------------------------- This script is designed for Microsoft SQL Server 2000 (8.0) but your database is set up for compatibility with version ' + CAST(@DBCompatibilityLevelMajor AS NVARCHAR(80)) + N'.' + CAST(@DBCompatibilityLevelMinor AS NVARCHAR(80)) + N'. Although the script should work with later versions of Microsoft SQL Server, you can ensure compatibility by executing the following statement: ALTER DATABASE [' + DB_NAME() + N'] SET COMPATIBILITY_LEVEL = 80 If you are hosting ELMAH in the same database as your application database and do not wish to change the compatibility option then you should create a separate database to host ELMAH where you can set the compatibility level more freely. If you continue with the current setup, please report any compatibility issues you encounter over at: http://code.google.com/p/elmah/issues/list ===========================================================================' ENDGO/* ------------------------------------------------------------------------ TABLES ------------------------------------------------------------------------ */CREATE TABLE [dbo].[ELMAH_Error] ( [ErrorId] UNIQUEIDENTIFIER NOT NULL , [Application] NVARCHAR(60) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL , [Host] NVARCHAR(50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL , [Type] NVARCHAR(100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL , [Source] NVARCHAR(60) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL , [Message] NVARCHAR(500) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL , [User] NVARCHAR(50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL , [StatusCode] INT NOT NULL , [TimeUtc] DATETIME NOT NULL , [Sequence] INT IDENTITY(1, 1) NOT NULL , [AllXml] NTEXT COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL )ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]GOALTER TABLE [dbo].[ELMAH_Error] WITH NOCHECK ADD CONSTRAINT [PK_ELMAH_Error] PRIMARY KEY NONCLUSTERED ([ErrorId]) ON [PRIMARY] GOALTER TABLE [dbo].[ELMAH_Error] ADD CONSTRAINT [DF_ELMAH_Error_ErrorId] DEFAULT (NEWID()) FOR [ErrorId]GOCREATE NONCLUSTERED INDEX [IX_ELMAH_Error_App_Time_Seq] ON [dbo].[ELMAH_Error] ([Application] ASC,[TimeUtc] DESC,[Sequence] DESC) ON [PRIMARY]GO/* ------------------------------------------------------------------------ STORED PROCEDURES ------------------------------------------------------------------------ */SET QUOTED_IDENTIFIER ON GOSET ANSI_NULLS ON GOCREATE PROCEDURE [dbo].[ELMAH_GetErrorXml] ( @Application NVARCHAR(60) , @ErrorId UNIQUEIDENTIFIER )AS SET NOCOUNT ON SELECT [AllXml] FROM [ELMAH_Error] WHERE [ErrorId] = @ErrorId AND [Application] = @ApplicationGOSET QUOTED_IDENTIFIER OFF GOSET ANSI_NULLS ON GOSET QUOTED_IDENTIFIER ON GOSET ANSI_NULLS ON GOCREATE PROCEDURE [dbo].[ELMAH_GetErrorsXml] ( @Application NVARCHAR(60) , @PageIndex INT = 0 , @PageSize INT = 15 , @TotalCount INT OUTPUT )AS SET NOCOUNT ON DECLARE @FirstTimeUTC DATETIME DECLARE @FirstSequence INT DECLARE @StartRow INT DECLARE @StartRowIndex INT SELECT @TotalCount = COUNT(1) FROM [ELMAH_Error] WHERE [Application] = @Application -- Get the ID of the first error for the requested page SET @StartRowIndex = @PageIndex * @PageSize + 1 IF @StartRowIndex <= @TotalCount BEGIN SET ROWCOUNT @StartRowIndex SELECT @FirstTimeUTC = [TimeUtc] , @FirstSequence = [Sequence] FROM [ELMAH_Error] WHERE [Application] = @Application ORDER BY [TimeUtc] DESC , [Sequence] DESC END ELSE BEGIN SET @PageSize = 0 END -- Now set the row count to the requested page size and get -- all records below it for the pertaining application. SET ROWCOUNT @PageSize SELECT errorId = [ErrorId] , application = [Application] , host = [Host] , type = [Type] , source = [Source] , message = [Message] , [user] = [User] , statusCode = [StatusCode] , time = CONVERT(VARCHAR(50), [TimeUtc], 126) + 'Z' FROM [ELMAH_Error] error WHERE [Application] = @Application AND [TimeUtc] <= @FirstTimeUTC AND [Sequence] <= @FirstSequence ORDER BY [TimeUtc] DESC , [Sequence] DESC FOR XML AUTOGOSET QUOTED_IDENTIFIER OFF GOSET ANSI_NULLS ON GOSET QUOTED_IDENTIFIER ON GOSET ANSI_NULLS ON GOCREATE PROCEDURE [dbo].[ELMAH_LogError] ( @ErrorId UNIQUEIDENTIFIER , @Application NVARCHAR(60) , @Host NVARCHAR(30) , @Type NVARCHAR(100) , @Source NVARCHAR(60) , @Message NVARCHAR(500) , @User NVARCHAR(50) , @AllXml NTEXT , @StatusCode INT , @TimeUtc DATETIME )AS SET NOCOUNT ON INSERT INTO [ELMAH_Error] ( [ErrorId] , [Application] , [Host] , [Type] , [Source] , [Message] , [User] , [AllXml] , [StatusCode] , [TimeUtc] ) VALUES ( @ErrorId , @Application , @Host , @Type , @Source , @Message , @User , @AllXml , @StatusCode , @TimeUtc )GOSET QUOTED_IDENTIFIER OFF GOSET ANSI_NULLS ON GO
瀏覽器輸入地址http://localhost:5547/abc123ds
在數據庫輸入腳本并查看結果如下
SQLite與Oracle的配置與sql server類似,就不重復了,
相關腳本下載地址:https://code.google.com/p/elmah/downloads/list
2.4 手動記錄錯誤
方法:
ErrorSignal.FromCurrentContext().Raise()
現在我們創造2個錯誤并記錄
修改HomeController如下
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using Elmah;namespace Jean.ElmahSample.Controllers{ public class HomeController : Controller { // // GET: /Home/ public ActionResult Index() { try { var t = int.Parse("abc"); } catch (Exception e) { ErrorSignal.FromCurrentContext().Raise(e); // error 1 ErrorSignal.FromCurrentContext().Raise(new ArgumentNullException()); // error 2 } return View(); } }}
重新生成
瀏覽器輸入 http://localhost:5547
新開窗口輸入 http://localhost:5547/elmah.axd
結果如下
新聞熱點
疑難解答