elmah - Error Logging Modules and Handlers fo…
2018-06-18 03:27:56来源:未知 阅读 ()
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 INT DECLARE @DBCompatibilityLevelMajor INT DECLARE @DBCompatibilityLevelMinor INT SELECT @DBCompatibilityLevel = cmptlevel FROM master.dbo.sysdatabases WHERE 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 =========================================================================== ' END GO /* ------------------------------------------------------------------------ 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] GO ALTER TABLE [dbo].[ELMAH_Error] WITH NOCHECK ADD CONSTRAINT [PK_ELMAH_Error] PRIMARY KEY NONCLUSTERED ([ErrorId]) ON [PRIMARY] GO ALTER TABLE [dbo].[ELMAH_Error] ADD CONSTRAINT [DF_ELMAH_Error_ErrorId] DEFAULT (NEWID()) FOR [ErrorId] GO CREATE 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 GO SET ANSI_NULLS ON GO CREATE PROCEDURE [dbo].[ELMAH_GetErrorXml] ( @Application NVARCHAR(60) , @ErrorId UNIQUEIDENTIFIER ) AS SET NOCOUNT ON SELECT [AllXml] FROM [ELMAH_Error] WHERE [ErrorId] = @ErrorId AND [Application] = @Application GO SET QUOTED_IDENTIFIER OFF GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_NULLS ON GO CREATE 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 AUTO GO SET QUOTED_IDENTIFIER OFF GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_NULLS ON GO CREATE 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 ) GO SET QUOTED_IDENTIFIER OFF GO SET 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
结果如下
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
上一篇:最近修改的几个小bug
下一篇:解决jquery版本冲突问题
- Qt5 error LNK2019 无法解析的外部符号的解决办法 2020-02-14
- 编译x64c++出错,errorC1900:P1和P2之间 Il 不匹配问题 2020-01-14
- 类———用类定义对象———error:C++表达式必须包含类类型 2019-05-22
- VS2015 C++编译报错 error:LNK2005 _main 已经在 *.obj 中定 2019-02-25
- C++ Simple Message/Logging Class 2018-10-23
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash