Logging Errors in ASP.NET CORE 3.1 Using StackExchange.Exceptional Logger

In this article, we are going to learn how to log Errors in ASP.NET CORE and store them SQL Server database using StackExchange.Exceptional also showing logged errors in details.

The StackExchange.Exceptional is the error handler used internally by Stack Exchange and Stack Overflow for logging to SQL.

StackExchange.Exceptional provides various data storage such as

  • SQL Server
    It will Store Error in Microsoft SQL Server Database (Exceptions table).
  • MYSQL
    It will Store Error in MYSQL Database (Exceptions table).
  • JSON
    The Error will be stored in a json file. Can be only used for small application.
  • Memory
    The memory store is, by nature volatile and app-domain specific.

Let’s start

  • Creating ASP.NET Core Application
  • Installing StackExchange.Exceptional.AspNetCore from NuGet Package
  • Configuring Database and Tables
  • Configuring Exceptional Connection string in appsettings.json file
  • Registering AddExceptional service in ConfigureServices Method
  • Adding app.UseExceptional(); in Configure method to handle errors
  • Adding DemoController for throwing Exception
  • Run Application to Log Error
  • Adding a route handler to render your errors.
  • Output

Creating ASP.NET Core Application

We are going to develop ASP.NET Core Web Application for that we are going to choose ASP.NET Core Web Application template.

Next, we are going to set Project Name WebLoggerDemo and location. In last part, we are going to choose .Net Core framework and ASP.NET Core Version 3.1 as a framework for application and few advance settings for such as configuring https and enabling docker we are not going to enable docker settings for this project.

Now finally click on create button to create a project.

Project structure
The project structure generated according to the configuration.

After creating a project, we are going to run this project.

Installing StackExchange.Exceptional.AspNetCore from NuGet Package

For installing package just right click on solution Select Manage NuGet Packages after selecting NuGet Package Manager dialogue will pop up as shown below.
In that dialogue choose browse tab and in the search package StackExchange.Exceptional.AspNetCore and install the latest version of it.

After installing the package next, we are going to run a script for creating a table where errors are going to be stored.

Note: – I will be sharing script to download.

Configuring Database and Tables

After creating the table next, we are going to add Exceptional tag configuration in appsettings.json file which contains connection string for storing Error in Database.

"Exceptional": {
    "Store": {
      "ApplicationName": "WebLoggerDemo",
      "Type": "SQL",
      "ConnectionString": "Data Source=DESKTOP-DUM6D15;Database=SampleDB3;UID=sa;Password=Pass123"
    }
  }

appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "Exceptional": {
    "Store": {
      "ApplicationName": "WebLoggerDemo",
      "Type": "SQL",
      "ConnectionString": "Data Source=DESKTOP-DUM6D15;Database=SampleDB3;UID=sa;Password=Pass123"
    }
  }
}

After adding Exceptional tag configuration in appsettings.json file next, we are going to register service in ConfigureServices Method.

Registering AddExceptional service in ConfigureServices Method

To register service just we need to add below code.

services.AddExceptional(Configuration.GetSection("Exceptional"));

ConfigureServices

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();
    services.AddExceptional(Configuration.GetSection("Exceptional"));
}

To show the Exceptional page on throw, instead of the built-in .UseDeveloperExceptionPage()

public void ConfigureServices(IServiceCollection services)
 {
     services.AddControllersWithViews();

     services.AddExceptional(Configuration.GetSection("Exceptional"), settings =>
     {
         settings.UseExceptionalPageOnThrow = Env.IsDevelopment();
     });
 }

After adding ConfigureServices next, we are going to add UseExceptional middleware in Configure method.

Adding app.UseExceptional(); Middleware in Configure method to handle errors

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
 {
     app.UseExceptional();

     app.UseHttpsRedirection();
     app.UseStaticFiles();

     app.UseRouting();

     app.UseAuthorization();

     app.UseEndpoints(endpoints =>
     {
         endpoints.MapControllerRoute(
             name: "default",
             pattern: "{controller=Home}/{action=Index}/{id?}");
     });
 }

After adding UseExceptional Middleware Next, we are going to adding demo controller with index action in it.

Adding DemoController for throwing Exception

We have added the demo controller and index action, and in the index action method, we are going to throw NotImplementedException expectation.

using Microsoft.AspNetCore.Mvc;
using System;

namespace WebLoggerDemo.Controllers
{
    public class DemoController : Controller
    {
        public IActionResult Index()
        {
            throw new NotImplementedException();
            return View();
        }
    }
}

After adding the Controller and action method which throws next, we are going to run this application and access URL Demo/Index which will throw Error.

Run Application to Log Error

After running the application and accessing URL Demo/Index which will throw an error as shown below.

Now let’s see SQL is this Error logged which has occurred.

Now every time we cannot see SQL for expectation right.

StackExchange.Exceptional has Nice UI for rendering all these errors just we need to configure it one plus point StackExchange.Exceptional is that we can set show errors page after login means only admin or superadmin or developer can see errors UI you can configure it as you want.

Adding a route handler to render your errors

We are going to add route handler Exceptions, which will render Errors which are stored in Exceptions table.

public async Task Exceptions()
{
    await ExceptionalMiddleware.HandleRequestAsync(HttpContext).ConfigureAwait(false);
}

This handler can be called in any controller. For the demo I have added ShowErrors Controller inside that I have added route handler Exceptions.

using Microsoft.AspNetCore.Mvc;
using StackExchange.Exceptional;
using System.Threading.Tasks;

namespace WebLoggerDemo.Controllers
{
    public class ShowErrorsController : Controller
    {
        public async Task Exceptions()
        {
            await ExceptionalMiddleware.HandleRequestAsync(HttpContext).ConfigureAwait(false);
        }
    }
}

Now we just need to run application and access URL ShowErrors/Exceptions to see all errors which are stored in the Database.

Output

To see details of Error just click on Error Text.
If the same Error is thrown again and again, then it will show error thrown count.

Referenced from: – This article is referenced from https://github.com/NickCraver/StackExchange.Exceptional thanks to NickCraver for writing this cool component.

By