MVC uses the Elmah logging component, mvcelmah

Source: Internet
Author: User
Tags log4net

MVC uses the Elmah logging component, mvcelmah
Introduction

ELMAH (Error Logging Modules and Handlers) Error Logging module and processing program, is a widely used Error Log tool that is completely pluggable. It can be dynamically added to a running ASP. NET Web application, or even all ASP. NET Web applications on a machine without recompilation or redeployment.

ELMAH supports both ASP. NET Web Forms and ASP. net mvc. You can configure ELMAH to store various errors (XML files, Event Logs, Access databases, SQL databases, Oracle databases, or computer RAM .) You can also ask ELMAH to email you the error message when an error occurs.

By default, in a website with ELMAH installed, you can access elmah by requesting the ELMAH. axd page.

Usage

This article attempts to use Elmah in Asp.net MVC 5.

Step 1: Install deployment

First, Build an empty Asp.net MVC 5 Project:

 

Add Elmah reference:

Elmah has been successfully configured. In fact, this process has done two things:

  • A: Copy Elmah. dll to the Bin folder in the root directory of the program and reference the current project.
  • B: Add the following content to the Web. Config file under the project root directory:

Add the following content to the webConfig file:

  <configSections>    <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><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>      Step 2: Test and use

HomeController. cs

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;namespace Elmah.Demo.Controllers{    public class HomeController : Controller    {        //        // GET: /Home/        public ActionResult Index()        {            return View();        }        [HttpPost]        public ActionResult GenerateError(string error)        {            throw new ApplicationException(error);        }    }}

Index. cshtml

@ {Layout = null; ViewBag. title = "Index ";} <div> <input type = "text" id = "ErrorMsg"/> <button id = "GenerateError"> Generate error logs </button> <a href = "/elmah. axd "target =" _ blank "> View error logs in elmah </a> </div> <script src = "~ /Scripts/jquery-1.10.2.js "> </script> <script type =" text/javascript ">$ (" # GenerateError "). click (function () {$. post ("/Home/GenerateError? Error = "+ $ (" # ErrorMsg "). val () ;}); </script>

The running effect is as follows:

If it is not Post, yellow pages will be reported, such:

Let's see if Elmah records exceptions during this execution:

Elmah has caught exceptions in the current application as scheduled. ELMAH records error information in the background and provides an interface for us to query error log information. It only requires simple operations to complete basic requirements.

Storage Method

Someone may ask, the log storage method is not specified in the automatic configuration above (of course, the configuration is not described here, but from the configuration above, it seems that no storage method is specified.) Where is the data stored? The answer is that after NuGet installs ELMAH, it does not specify any storage mode. ELMAH believes that if the storage method is not specified, the defaultMemory storage method (can also be explicitly specified). However, this storage method can only be used in the debugging stage. This method should not be used in the production environment. For specific disadvantages, see Introduction to memory storage methods.

Next, we will introduce various storage methods in detail. Taking database storage, file storage, and memory storage as examples, we need to emphasize that ELMAH currently only supports either of the three methods, multiple record methods are not supported at the same time. (Presumably this is not necessary)

1. Memory storage

Memory storage, as its name implies, records logs in the memory allocated to applications by the operating system. The application memory is related to the application domain, which ensures that each application can only obtain and record its own log information. However, once the application is restarted, the previously recorded information will disappear. In the simplest example, if you use this method for debugging, ASP is used by default. NET Development Server is used as a web Server. If the Server is stopped at this time, the above conditions are met (for example ). In addition, problems such as power failure and IIS restart after the release will cause loss of recorded information. Therefore, this method can only be used for testing.

In fact, the Elmah processing principle. when an error is reported on the request page. when a yellow page error is returned, it is intercepted by the ErrorLog module in httpModules. this module saves information about this request error. -The default value is stored in the memory. it facilitates instant debugging. but the user enters elmah. when the axd wants to view log information. first, httpHandlers captures the request. and hand it to elmah. axd processing program. this module returns the error log View to the user. it can be seen that the core Elmah technology is implemented based on HttpModules and HttpHandlers.

2. File Storage

In fact, ELMAH provides an xml file storage method,Generates an xml file for each error log.. The configuration is quite simple:

<Elmah> <! -- See http://code.google.com/p/elmah/wiki/SecuringErrorLogPages for more information on remote access and securing ELMAH. --> <security allowRemoteAccess = "false"/> <! -- This is the only line, where logPath is used to specify the location of the log folder --> <errorLog type = "Elmah. XmlFileErrorLog, Elmah" logPath = "~ /Static/Log/"/> </elmah>

This configuration must ensure that the LogPath directory exists completely. The test will find an XML file in the local file (\ Elmah. Demo \ Static \ Log:

3. database storage

In terms of data visualization and management, the database is still the ideal choice. Here we use the SQlServer2008 version for testing. To build Elmah to support SQLServer data, we need to perform the following three operations:

  • A) Tell ELMAH which database to use as the storage database;
  • B) Tell ELMAH how to connect to the database;
  • C) the specified database must contain tables, views, and stored procedures required by ELMAH (this process is not required for Embedded databases ).

Steps a and B must be specified in web. config, and c must add related objects to the database.

The web. config configuration is as follows (httpModules and httpHandlers will not be pasted, here only the configuration of ELMAH record logs in sqlserver database is provided ):

 

<ConnectionStrings> <add name = "elmah-sqlserver" connectionString = "server = .; database = MvcTest; user id = sa; password = 111111 @ a "providerName =" System. data. sqlClient "/> </connectionStrings> <elmah> <! -- See http://code.google.com/p/elmah/wiki/SecuringErrorLogPages for more information on remote access and securing ELMAH. --> <security allowRemoteAccess = "false"/> <! -- This is the only line, where logPath is used to specify the folder location for logging --> <! -- <ErrorLog type = "Elmah. XmlFileErrorLog, Elmah" logPath = "~ /Static/Log/"/> --> <! -- Tell elmah that I want to use sqlserver to record my logs. The string connecting to that database is named myconnectionString. --> <ErrorLog type = "Elmah. SqlErrorLog, Elmah" connectionStringName = "elmah-sqlserver"/> </elmah>

 

Create a database and execute the following SQL statement on the data. See the official connection.

Elmah SQL Server Script File:http://code.google.com/p/elmah/source/browse/src/Elmah/SQLServer.sql

Script:

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]GOSET QUOTED_IDENTIFIER ON GOSET ANSI_NULLS ON GOCREATE PROCEDURE dbo.ELMAH_GetErrorXml(    @Application NVARCHAR(60),    @ErrorId UNIQUEIDENTIFIER)ASSET NOCOUNT ONSELECT     AllXmlFROM     ELMAH_ErrorWHERE    ErrorId = @ErrorIdAND    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 ONDECLARE @FirstTimeUTC DateTimeDECLARE @FirstSequence intDECLARE @StartRow intDECLARE @StartRowIndex int-- Get the ID of the first error for the requested pageSET @StartRowIndex = @PageIndex * @PageSize + 1SET ROWCOUNT @StartRowIndexSELECT      @FirstTimeUTC = TimeUTC,    @FirstSequence = SequenceFROM     ELMAH_ErrorWHERE       Application = @ApplicationORDER BY     TimeUTC DESC,     Sequence DESC-- Now set the row count to the requested page size and get-- all records below it for the pertaining application.SET ROWCOUNT @PageSizeSELECT     @TotalCount = COUNT(1) FROM     ELMAH_ErrorWHERE     Application = @ApplicationSELECT     errorId,     application,    host,     type,    source,    message,    [user],    statusCode,     CONVERT(VARCHAR(50), TimeUtc, 126) + 'Z' timeFROM     ELMAH_Error errorWHERE    Application = @ApplicationAND     TimeUTC <= @FirstTimeUTCAND     Sequence <= @FirstSequenceORDER BY    TimeUTC DESC,     Sequence DESCFOR    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)ASSET NOCOUNT ONINSERTINTO    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

After the SQL statement is executed, the table is displayed in the current database:

When you run the application again. query the database in Throw ArgumentNullException:

A brief summary of various methods:
  • The database storage method is difficult to configure, but the efficiency is the best for large-scale log records;
  • The file storage method is relatively simple. One file is recorded every day. When the data volume is large, it may cause efficiency problems caused by massive files;
  • Memory storage and configuration are the easiest. However, it should not be used in the production environment for the above reasons.
Supplement

Some features are introduced during the use of Elmah.

Elmah records and displays exceptions captured by programs through Http Modules and Http Handler. however, if you add an exception handling module to the application. try-Catch Elmah cannot be recorded. or after Catch, it is thrown in Throw. on the exception chain of the entire application. only the final exception can be captured and recorded by the Elmah component when it is thrown to the Asp.net runtime.

Many people think that the Elmah component can handle application exceptions. in essence, Elmah is essentially a logging tool. no exception handling capability. therefore, if an exception occurs. it will not change the user experience provided by the original application. the yellow page still appears.

The official Note explicitly mentions an exception:

ELMAH exception capture is an Error event based on the HttpApplication object.

If some processing in the software project causes the HttpApplication event to fail to be triggered (for example, if the Application_Error has not been executed before an exception occurs, the Server. ClearError () method is executed,

It will prevent the triggering of the Error event. For example, if an exception is caught by try-catch and throw is not thrown again, the exception will not trigger the Error event)

There are still a lot of logging tools, such as the famous Log4net. Log4Net contains four main components: Logge, Repository, Appender, and Layout. powerful functions. you can customize the log output level. for more information, see my other article:

Configure and use Log4net

 

Source code is provided. The source code is stored in memory by default. You need to change it to a file or database. Modify the corresponding configuration that has been commented out under the <elmah> node. Click to download

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.