How to use Elmah for error logging in ASP.Net Core

Take advantage of Elmah logging framework and the Elmah.io log monitoring service to manage errors in your ASP.Net Core application

Error management is an integral part of any application. Elmah (which stands for Error Logging Modules and Handlers) is a pluggable error management framework. Because Elmah can be used to attach error logging capabilities to your application without having to re-compile or re-deploy, it makes the process of detecting application errors almost seamless.

In this article we’ll look at how to implement error management in ASP.Net Core using the Elmah error management framework and Elmah.io, a cloud-based error management system that works with Elmah. Elmah.io indexes all your errors for searching and provides a dashboard for issue tracking. Plus Elmah.io integrates nicely with many other popular logging frameworks including NLog and Log4net.

Elma.io pricing starts at $26 per month, after a 21 day free trial. To leverage Elmah.io in your ASP.Net Core application, start by creating an account and setting up a log. To create the log, you can take a look at the Elma.io documentation available here for reference. The next step is to install the necessary packages in your ASP.Net Core application as discussed in the section that follows.

Creating an ASP.Net Core application

Assuming that you’re running Visual Studio Community Edition 2017 and .Net Core is already installed in your system, you can take advantage of the steps that follow to create an ASP.Net Core application. Note that Elmah is not compatible with ASP.Net Core 1.0. We will use ASP.Net Core 2.0 in this example.

  1. In the Visual Studio IDE, click on File > New > Project.
  2. Select "ASP.Net Core Web Application (.Net Core)" from the list of templates displayed.
  3. Specify a name for the project.
  4. Click OK to save the project.
  5. Select “Web API” in the "New .Net Core Web Application…" window.
  6. Uncheck the "Enable Docker Support" checkbox.
  7. Select "No Authentication" as we won’t be using authentication in this example.
  8. Click OK.

Now select the project in the Solution Explorer window and then add the Elmah.Io.AspNetCore and the Elmah.Io.Extensions.Logging NuGet packages via the NuGet Package Manager. While the former is used to catch unhandled exceptions, the latter is used for logging messages. Note that the Elmah.Io.Extensions package leverages the built-in ILoggerFactory for logging messages. Note that although you can log messages of any type, it is recommended that you log only warnings, critical messages, and errors.

Configuring Elmah in ASP.Net Core

You can configure Elmah using the Configure method in the Startup.cs file. Note the usage of the apiKey parameter that you need to pass to the UseElmahIo method. In the code snippet below, note how the host name and application name are specified.

app.UseElmahIo(apiKey, new Guid(logId),
            new ElmahIoSettings()
            {
                OnMessage = msg =>
                {
                    msg.Version = "1.0.0";
                    msg.Hostname = "dev";
                    msg.Application = "IDGAspNetCoreUsingElmah";
                }
            });

You can read the apiKey and the logId values from the configuration file as well. The following code snippet illustrates how this can be achieved using the ConfigureServices method in the Startup.cs file.

public void ConfigureServices(IServiceCollection services)
        {
            apiKey = Configuration["ApiKey"];
            logId = Configuration["LogId"];
            // Add framework services.
            services.AddMvc();
        }

And that's it! Once your application is started, you will be able to view the errors and exceptions that have been logged in your Elmah.io dashboard.

Using NLog with Elmah in ASP.Net Core

You can also use NLog to log data to Elmah.io. To do this, you should install the Elmah.Io.NLog NuGet package in your project using the NuGet Package Manager. Alternatively, you can add the package references directly in the project file as shown below.

<PackageReference Include="Elmah.Io.NLog" Version="3.1.41" />
<PackageReference Include="NLog.Web.AspNetCore" Version="4.5.3" />

Next you must configure NLog in the Startup.cs file or the nlog.config file. You can also configure the nlog.config file for the target, appropriately specifying the Elmah.io type. The following code snippet illustrates how you can configure NLog with Elmah.io in the Configure method of the Startup class (pertaining to the Startup.cs file).

loggerFactory.AddNLog();
app.AddNLogWeb();
LogManager.Configuration.Variables["configDirectory"] = configDirectory;
foreach (var target in LogManager.Configuration.AllTargets.Where(target => target is ElmahIoTarget))
 {
   target.ApiKey = apiKey;
   target.LogId = logId;
 }
LogManager.ReconfigExistingLoggers();

Using the Error Logging Middleware in ASP.Net Core

You can also take advantage of middleware available in the Microsoft.AspNetCore.Diagnostics package. The Error Logging Middleware (ELM) in ASP.Net Core supports some of the capabilities of Elmah. To use Error Logging Middleware in your application, you should add the following two middleware components in the Configure method of the Startup.cs file.

app.UseElmPage();
app.UseElmCapture();

You should also add the ElmLoggerProvider service in the ConfigureServices method as shown below.

public void ConfigureServices(IServiceCollection services)
{
    //Other services
    services.AddElm();
    services.AddMvc();
}

Elmah is a great way to log the unhandled exceptions in your application. It lets you log errors in SQL Server, Oracle, SQLite, MySQL, PostgreSQL, and even XML files. If you add Elmah.io to the mix, you can view the error logs in a web page remotely and even receive notifications on the errors if need be.

Copyright © 2018 IDG Communications, Inc.