×

iFour Logo

How to use ELMAH for enumerating error in ASP.NET core?

Kapil Panchal - October 20, 2020

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

  • play
  • pause
  • pause
How to use ELMAH for enumerating error in ASP.NET core?

Introduction to ELMAH


ELMAH Stands for Error Logging Modules and Handlers that offers functionality to logging runtime ASP.NET errors. ELMAH can be utilizing to adjoin error logging abilities in your application without having to re-compile or re-deploy, it creates the process of capturing application errors seamlessly.

When added to a running web application on a machine, exceptions that are thrown trigger event handlers in the ELMAH tool. These event handlers can include logging to various database back-ends, logging which can be viewed from a web portal, and the sending of notification emails, tweets and RSS articles to advise administrators of the problem. ELMAH provides a pluggable implementation of error logging.

An alternative to the health monitoring system is Error Logging Modules and Handlers (ELMAH), a free, open-source error logging system created by Atif Aziz. 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.

Hereby, we will look at how to execute error management in ASP.Net Core using the ELMAH error management framework and Elmah.io, a cloud-based error management system that toils with ELMAH.

  • Elmah.io indexes all your errors for searching and offers a dashboard for issue tracking. Additionally, Elmah.io unites nicely with many other admired logging frameworks involving NLog and Log4net.
  • Before the .Net Core was launched with its Middleware architecture, the most appropriate way for logging errors in the web application was ELMAH or similar.
  • But since .Net Core has distinct architecture, not module based, but middleware based, the ELMAH is not in action any more.

This article depicts how to integrate a simple logger very similar to ELMAH that stores latest errors in memory.

Why to choose ELMAH?


  • ELMAH empowers logging of all unhandled exceptions.
  • ELMAH logs all errors in many storages, like - SQL Server, MySQL, Random Access Memory (RAM), SQL Lite, and Oracle.
  • ELMAH has functionality to download all errors in CSV file.
  • Acquire all error data in JSON or XML format
  • Dispatch error log notification to your application
  • Customize the error log by personalizing some code

Logging to elmah.io from ASP.NET Core


You can add logs, exceptions to elmah.io directly from an ASP.NET Core application using the Elmah.Io.ASPNetCore packages. These packages can be added to the project using the nuget package manager.

Now Call AddElmahIo in the ConfigureServices-method in the Startup.cs file

Replace API_KEY with your API key and LOG_ID. with the log Id of the log you want to log to.

Call UseElmahIo in the Configure-method in the Startup.cs file:

public void ConfigureServices(IServiceCollection services)
{
      services.AddElmahIo(o =>
      {
          o.ApiKey = "API_KEY";
          o.LogId = new Guid("LOG_ID");
      });
}
public void Configure (IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory fac)
{
      app.UseElmahIo();
     
}
    

Configuring API key and log ID in options


Now if you have different environments, you should consider adding the API key and log ID in your appsettings.json file

{

"ElmahIo": 
{
  "ApiKey": "API_KEY",
  "LogId": "LOG_ID"
}

Now Configuring elmah.io is done by calling the Configure method and instead of AddElmahIo. And Finally, call the UseElmahIo method.

public void ConfigureServices(IServiceCollection services)
{
  services.Configure(Configuration.GetSection("ElmahIo"));
  services.AddElmahIo();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
      
  app.UseElmahIo();
      
}

You can still configure additional options on the ElmahIoOptions object


public void ConfigureServices(IServiceCollection services)
{
    services.Configure(Configuration.GetSection("ElmahIo"));
    services.Configure(o =>
    {
      o.OnMessage = msg =>
        {
          msg.Version = "2.1.0";
        };
    });
    services.AddElmahIo();
}

Additional options


Events

elmah.io for ASP.NET Core supports a range of events for hooking into the process of logging messages. Events are registered as actions when installing the elmah.io middleware:

      services.AddElmahIo(o =>
{
  o.ApiKey = "API_KEY";
  o.LogId = new Guid("LOG_ID");
  o.OnMessage = message =>
  {
      message.Version = "40";
  };
o.OnError = (message, exception) =>
{
      logger.Lo?gError(1, exception, "Error during log to elmah.io");
};
});

The actions provide a mechanism for hooking into the log process. The action registered in the OnMessage property is called by elmah.io just before logging a new message to the API.

Use this action to decorate/enrich your log messages with additional data, like a version number. The OnError action is called if communication with the elmah.io API failed.

Now While elmah.io supports ignore rules serverside, you may want to filter out errors without even hitting the elmah.io API. Using the OnFilter function on the options object, filtering is easy:

services.AddElmahIo(o =>
{
  
  o.OnFilter = message =>
  {
      return message.Type == "System.NullReferenceException";
  };
});

Remove sensitive form data

The OnMessage event can be used to filter sensitive form data as well. In the following example, we can remove the server variable named Secret-Key from all messages, before sending them to elmah.io

  services.AddElmahIo(options =>
{
  options.ApiKey = "API_KEY";
  options.LogId = new Guid("LOG_ID");

  options.OnMessage = msg =>
{
    var item = msg.ServerVariables.FirstOrDefault(x => x.Key == "Secret-Key"); 
    if (item != null)
{
  msg.ServerVariables.Remove(item);
}
};
});

Looking to Hire ASP.Net Core Developer ? Contact Now

Logging exceptions, errors to elmah.io using NLog


NLog using the Elmah.Io.NLog target can also be used in ASP.NET Core to send messages to elmah.io. This can be added using the nuget package manager.

elmah_IO

NLog for ASP.NET Core applications can be configured in the Startup class. You need to set the target properties with the elmah.io API-KEY and also the LogId. You could also do this in the nlog.config file

Conclusion


Elmah is a perfect way to log the unhandled exceptions in your application. It assists you log errors in SQL Server, Oracle, SQLite, MySQL, PostgreSQL, and even XML files. If you adjoin Elmah.io to the mix, you can review the error logs in a web page remotely and even acquire notifications on the errors if require.

Signup here to learn more about elmah.io

How to use ELMAH for enumerating error in ASP.NET core? Table of Content 1. Introduction to ELMAH 2. Why to choose ELMAH? 3. ELMAH HTTP Modules 4. Logging to elmah.io from ASP.NET Core 5. Configuring API key and log ID in options 6. Additional options 6.1. Events 6.2. Remove sensitive form data 7. Logging exceptions, errors to elmah.io using NLog 8. Conclusion Introduction to ELMAH ELMAH Stands for Error Logging Modules and Handlers that offers functionality to logging runtime ASP.NET errors. ELMAH can be utilizing to adjoin error logging abilities in your application without having to re-compile or re-deploy, it creates the process of capturing application errors seamlessly. When added to a running web application on a machine, exceptions that are thrown trigger event handlers in the ELMAH tool. These event handlers can include logging to various database back-ends, logging which can be viewed from a web portal, and the sending of notification emails, tweets and RSS articles to advise administrators of the problem. ELMAH provides a pluggable implementation of error logging. An alternative to the health monitoring system is Error Logging Modules and Handlers (ELMAH), a free, open-source error logging system created by Atif Aziz. 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. Hereby, we will look at how to execute error management in ASP.Net Core using the ELMAH error management framework and Elmah.io, a cloud-based error management system that toils with ELMAH. Elmah.io indexes all your errors for searching and offers a dashboard for issue tracking. Additionally, Elmah.io unites nicely with many other admired logging frameworks involving NLog and Log4net. Before the .Net Core was launched with its Middleware architecture, the most appropriate way for logging errors in the web application was ELMAH or similar. But since .Net Core has distinct architecture, not module based, but middleware based, the ELMAH is not in action any more. This article depicts how to integrate a simple logger very similar to ELMAH that stores latest errors in memory. Why to choose ELMAH? ELMAH empowers logging of all unhandled exceptions. ELMAH logs all errors in many storages, like - SQL Server, MySQL, Random Access Memory (RAM), SQL Lite, and Oracle. ELMAH has functionality to download all errors in CSV file. Acquire all error data in JSON or XML format Dispatch error log notification to your application Customize the error log by personalizing some code ELMAH HTTP Modules There are three HTTP Modules. 1. ErrorMailModule- is used for sending the details of log as an email. 2. ErrorLogModule- is used for logging all the exceptions and a few other details, such as IP- Address, Username, Website Username etc. 3. ErrorFilterModule- is used to personalize the exception logs. Logging to elmah.io from ASP.NET Core You can add logs, exceptions to elmah.io directly from an ASP.NET Core application using the Elmah.Io.ASPNetCore packages. These packages can be added to the project using the nuget package manager. Read More: New Features Of Asp.net Core For Modern Web And Cloud Applications Development Now Call AddElmahIo in the ConfigureServices-method in the Startup.cs file Replace API_KEY with your API key and LOG_ID. with the log Id of the log you want to log to. Call UseElmahIo in the Configure-method in the Startup.cs file: public void ConfigureServices(IServiceCollection services) { services.AddElmahIo(o => { o.ApiKey = "API_KEY"; o.LogId = new Guid("LOG_ID"); }); } public void Configure (IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory fac) { app.UseElmahIo(); } Configuring API key and log ID in options Now if you have different environments, you should consider adding the API key and log ID in your appsettings.json file { "ElmahIo": { "ApiKey": "API_KEY", "LogId": "LOG_ID" } Now Configuring elmah.io is done by calling the Configure method and instead of AddElmahIo. And Finally, call the UseElmahIo method. public void ConfigureServices(IServiceCollection services) { services.Configure(Configuration.GetSection("ElmahIo")); services.AddElmahIo(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseElmahIo(); } You can still configure additional options on the ElmahIoOptions object public void ConfigureServices(IServiceCollection services) { services.Configure(Configuration.GetSection("ElmahIo")); services.Configure(o => { o.OnMessage = msg => { msg.Version = "2.1.0"; }; }); services.AddElmahIo(); } Additional options Events elmah.io for ASP.NET Core supports a range of events for hooking into the process of logging messages. Events are registered as actions when installing the elmah.io middleware: services.AddElmahIo(o => { o.ApiKey = "API_KEY"; o.LogId = new Guid("LOG_ID"); o.OnMessage = message => { message.Version = "40"; }; o.OnError = (message, exception) => { logger.Lo?gError(1, exception, "Error during log to elmah.io"); }; }); The actions provide a mechanism for hooking into the log process. The action registered in the OnMessage property is called by elmah.io just before logging a new message to the API. Use this action to decorate/enrich your log messages with additional data, like a version number. The OnError action is called if communication with the elmah.io API failed. Now While elmah.io supports ignore rules serverside, you may want to filter out errors without even hitting the elmah.io API. Using the OnFilter function on the options object, filtering is easy: services.AddElmahIo(o => { o.OnFilter = message => { return message.Type == "System.NullReferenceException"; }; }); Remove sensitive form data The OnMessage event can be used to filter sensitive form data as well. In the following example, we can remove the server variable named Secret-Key from all messages, before sending them to elmah.io services.AddElmahIo(options => { options.ApiKey = "API_KEY"; options.LogId = new Guid("LOG_ID"); options.OnMessage = msg => { var item = msg.ServerVariables.FirstOrDefault(x => x.Key == "Secret-Key"); if (item != null) { msg.ServerVariables.Remove(item); } }; }); Looking to Hire ASP.Net Core Developer ? Contact Now See here Logging exceptions, errors to elmah.io using NLog NLog using the Elmah.Io.NLog target can also be used in ASP.NET Core to send messages to elmah.io. This can be added using the nuget package manager. NLog for ASP.NET Core applications can be configured in the Startup class. You need to set the target properties with the elmah.io API-KEY and also the LogId. You could also do this in the nlog.config file Conclusion Elmah is a perfect way to log the unhandled exceptions in your application. It assists you log errors in SQL Server, Oracle, SQLite, MySQL, PostgreSQL, and even XML files. If you adjoin Elmah.io to the mix, you can review the error logs in a web page remotely and even acquire notifications on the errors if require. Signup here to learn more about elmah.io See here

Build Your Agile Team

Enter your e-mail address Please enter valid e-mail

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 

Blog Our insights

Azure DevOps Pipeline Deployment for Competitive Business: The Winning Formula
Azure DevOps Pipeline Deployment for Competitive Business: The Winning Formula

We always hear about how important it is to be competitive and stand out in the market. But as an entrepreneur, how would you truly set your business apart? Is there any way to do...

React 18 Vs React 19: Key Differences To Know For 2024
React 18 Vs React 19: Key Differences To Know For 2024

Ever wondered how a simple technology can spark a revolution in the IT business? Just look at React.js - a leading Front-end JS library released in 2013, has made it possible. Praised for its seamless features, React.js has altered the way of bespoke app development with its latest versions released periodically. React.js is known for building interactive user interfaces and has been evolving rapidly to meet the demands of modern web development. Thus, businesses lean to hire dedicated React.js developers for their projects. React.js 19 is the latest version released and people are loving its amazing features impelling them for its adoption.

React 19 For Business: Latest Features and Updates
React 19 For Business: Latest Features and Updates

When I first started exploring React.js for my company’s needs, I felt a bit lost. It was like trying to solve a big puzzle without all the pieces! But as I kept learning and trying them practically, I discovered some really cool features that blew my mind making everything seamlessly easier.