Home > DeveloperSection > Articles > ELMAH in Asp.Net MVC

ELMAH in Asp.Net MVC


ASP.Net ASP.Net 
Ratings:
0 Comment(s)
 2930  View(s)
Rate this:

ELMAH in Asp.Net MVC

In this article describe the concept of elmah in mvc. ELMAH is stands form Error Logging and Handlers.

Here we describe an example of elmah in mvc.

ELMAH (Error Logging Modules and Handlers) is an open source error logging framework for ASP.NET and for ASP.NET MVC. When added to the web application, exceptions that are thrown will trigger event handlers in the ELMAH that will log nearly all unhandled exceptions.

ELMAH (Error logging Modules and Handlers) is an application wide error logging facility that is a pluggable framework. It can dynamically added to running an ASP.NET application. The most notable difference between the two systems is ELAMH's ability to display a list of errors and the details of a specific error from a web page and as an RSS feed. ELMAH is easier to configure than health monitoring because it only logs errors.

There are following advantages of elmah:

·         You can log almost all unhandled exceptions in the system.

·         An RSS feed of last 15 errors from the log

·         An email notification of each error occurs.

·         A remote web page to log all the exceptions.

·         You can insert log a various locations like files text file, SQL Server, Oracle etc.

How to install Elmah

First of all we create an mv application.

ELMAH in Asp.Net MVC 

Here we select the internet application:

ELMAH in Asp.Net MVC

 

Once you click ok button it will create new ASP.NET MVC 4 application is ready to use. After that we should add or install the ELMAH. We can add from package manager by command “Install-Package elmah” or we install from the ‘Mange NuGet Packages…’ from the project to right click. And find the ELMAH and install it.

 

ELMAH in Asp.Net MVC

 

Start by registering the ErrorLogModule HTTP Module and the ErrorLogPageFactory HTTP Handler in the <httpModules> and <httpHandlers> section in <system.web>. If your configuration already defines these two elements then simply include the <add> element for ELMAH's HTTP Module and Handler.

<configuration>

 

  …

  <system.web>

    <httpHandlers>

       …

      <add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah"/>

    </httpHandlers>

 

    <httpModules>

      …

     <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" />

    </httpModules>

 

  </system.web>

</configuration> 

Next, register ELMAH's HTTP Module and Handler in the <system.webServer> element. As before, if this element is not already present in your configuration then add it.

<configuration>

 

  …

  <system.webServer>

    <validation validateIntegratedModeConfiguration="false" />

    <handlers>

       …

<add name="Elmah" path="elmah.axd" verb="POST,GET,HEAD" type="Elmah.ErrorLogPageFactory, Elmah" preCondition="integratedMode" />

    </handlers>

    <modules>

        …

      <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah"preCondition="managedHandler" />

     

    </modules>

  </system.webServer>

</configuration> 

We also configure the section in web.config file:

<configuration>

  <configSections>

   

    <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>

</configuration> 

The above syntax registers the custom <elmah> section and its subsections: <security>, <errorLog>, <errorMail>, and <errorFilter>.

Next, add the <elmah> section to Web.config. This section should appear at the same level as the <system.web> element. Inside the <elmah> section add the <security> and <errorLog> sections like so:

<configuration>

    …

 

  <elmah>

 

    <security allowRemoteAccess="0"></security>

 

    <errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="DefaultConnection" />

 

</elmah>

   …

</configuration>

 

The <security> section’s allowRemoteAccess attribute indicates whether remote access is allowed. When this value is set to 0, then the error log web page can only be viewed locally and when this attribute is set to 1 then the error log web page is enabled for both remote and local visitors.

The <errorLog> section defines the error log source, which dictates where the error details are recorded; it is similar to the <providers> section in the health monitoring system. The above syntax specifies the SqlErrorLog class as the error log source, which logs the errors to a Microsoft SQL Server database specified by the connectionStringName attribute value.

Creating the structure of Error Log:

ELMAH in Asp.Net MVC

Action in Elmah

At this point we have added ELMAH to the web application, registered the ErrorLogModule HTTP Module and the ErrorLogPageFactory HTTP Handler, specified ELMAH's configuration options in Web.config, and added the needed database objects for the SqlErrorLog error log provider.

ELMAH doesn't affect what content is shown to the user when an unhandled exception occurs; it just logs its details. This error log is accessible from the web page elmah.axd from the root of your website, such as http://localhost:56585/elmah.axd. (This file does not physically exist in your project, but when a request comes in for elmah.axd the runtime dispatches it to the ErrorLogPageFactory HTTP Handler, which generates the markup sent back to the browser.)

ELMAH in Asp.Net MVC

Here we create an example of elmah validataion in mvc:

First create mvc application:

ELMAH in Asp.Net MVC

Create mvc application:

 ELMAH in Asp.Net MVC

Create mvc application as need. Here we create the LoginModels that contain that is given below:

public class LoginModels

    {

        [Key]

        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]

        public int user_id { getset; }

        [StringLength(15)]

        [Required(ErrorMessage = "Please enter the correct user name.")]

        public string user_name { getset; }

        [StringLength(15)]

        [Required(ErrorMessage="Please enter the correct password.")]

        public string user_password { getset; }

    }

 

And create context model

public class ContextModels:DbContext

    {

        public ContextModels(): base(nameOrConnectionString:@"Data Source=.\SQLEXPRESS;Initial Catalog=ELMAHValidationDB;Integrated Security=True;")

    {

    }

        public DbSet<LoginModels> Login {get;set;}

        public DbSet<SignUpModels> SignUpModels {get;set;}

    }

 

Install elmah validation from the Manage NuGet Package.. or install from the command package console manager.

ELMAH in Asp.Net MVC

 

In the article we describe the settings of we configuration for elmah validation apply the web.config file and if you want to send exception to email, to database, to the file in the below code:

<elmah>

    <errorLog type="Elmah.XmlFileErrorLog, Elmah" logPath="basedirectory\App_Data\" /> // either it use

    <errorFilter>

      <test>

        <or>

          <equal binding="HttpStatusCode" value="404" type="Int32" />

          <regex binding="BaseException.Message" pattern="The file '/[^']+' does not exist" />

        </or>

      </test>

    </errorFilter>

    <security allowRemoteAccess="0"></security>

    <errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="SampleLoginDB" />// or it use

   

    <errorMail

        from="test@gmail.com"

         to="test@gmail.com"

         subject="Error"

         async="true"

         smtpPort="25"

         useSsl="true"

         host="smtp.gmail.com"

         userName="test@gmail.com"

         password="***"/>

  </elmah>

  <system.net>

    <mailSettings>

      <smtp deliveryMethod ="Network">

        <network host="smtp.gmail.com" port="25" userName="test@gmail.com"   password=""/>

      </smtp>

    </mailSettings>

  </system.net>

 

In this given code all errorlog all possible statement codes like sqlserver and file log file, and the email validatation and security also provided.

You run the application if you get any error then elmah validation store on email via file via the database and also show the elmah.axd as like this.ELMAH in Asp.Net MVC

I hope this article will help to understand the elmah validation.


Don't want to miss updates? Please click the below button!

Follow MindStick