Updated on

Exceptionless is an open-source service that collects the errors, log messages and feature usage events our applications send to it. In ASP.NET Core, one NuGet package and a few lines in Program.cs are enough to report every unhandled exception to its dashboard.

To download the source code for this article, you can visit our GitHub repository.

So let’s get started.

What Is Exceptionless?

Exceptionless is an open-source error and event reporting service. Once we integrate it into our applications, it helps us monitor and fix the exceptions that happen inside them.

One of its most useful features is that it collects and reports unhandled exceptions automatically. We can also use it to capture feature usage, log messages and other custom events in real time.

Exceptionless supports a wide range of platforms, including .NET, JavaScript and Node.js, so one tool can watch different parts of an application stack. It offers both a cloud-hosted service and a self-hosted option, which gives us a choice in how we deploy and manage it.

In short, we can see what is happening with our application in production and find issues quickly. Exceptionless gives us rich diagnostic data, including stack traces, request information and custom objects, which makes problems easier to diagnose and fix.

Is Exceptionless Free?

Exceptionless is free for a small project, and the code is free either way. The .NET client packages are open source under the Apache-2.0 licence, and so is the Exceptionless server, which we can host ourselves.

The hosted service has a free plan. It covers 1 project and 1 user, keeps events for 3 days and accepts 3,000 events per month. Paid plans start at $15 per month for 5 projects, 10 users, 30 days of retention and 15,000 events.

The free plan leaves out what the pricing page calls premium features: searching, error occurrence notifications (free accounts get daily summaries only), and the webhook, Slack and Zapier integrations. We will meet all three later in this article, so it helps to know up front which ones need a paid plan.

Self-hosting is the other route, and then the server, its storage and its upgrades become ours to run.

Integrating Exceptionless With ASP.NET Core Web API

First, let’s create an ASP.NET Core Web API application with controllers, using either the dotnet new webapi --use-controllers -n ExceptionlessDemo command or the Visual Studio template with the controllers option checked. Without that option, the template now generates minimal APIs instead of controllers.

Create an Exceptionless Account & Project

Now let’s sign up for an Exceptionless account. There’s a self-hosted version as well, but the hosted version is easier to use and free to get started.

We can either create a new account or log in via an existing social account. After that, let’s create an Organization, then a Project inside it, and then find the API key in the API Keys tab of the Manage Project section:

Manage Project screen in Exceptionless

Let’s add the API key to the appsettings file of our Web API project:

{
  "Exceptionless": {
    "ApiKey": "{Our API Key here}"    
  },
  "Logging": {
...
  },
  "AllowedHosts": "*"
}

This will connect our application to the Exceptionless project that we just created.

Configure Exceptionless

Next, let’s configure the Exceptionless service.

For that, we need to first add the Exceptionless NuGet package to our project. There are different Exceptionless packages for working with different types of applications.

Let’s choose the ASP.NET Core variant:

dotnet add package Exceptionless.AspNetCore

After installing the package, let’s configure Exceptionless in the Program.cs file:

using Exceptionless;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddOpenApi();
builder.Services.AddProblemDetails();
builder.AddExceptionless();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();
}

app.UseExceptionHandler();
app.UseExceptionless();

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

app.Run();

Here, builder.AddExceptionless() registers an ExceptionlessClient that reads its settings from the Exceptionless section of our configuration. The Exceptionless guide for web servers says the call “registers the services needed to capture unhandled exceptions and request information”. In practice that means an IExceptionHandler implementation that reports unhandled exceptions, and a hosted service that sends any pending events before the host shuts down.

AddProblemDetails() and UseExceptionHandler() switch on the exception handling pipeline that this handler plugs into, and they turn an unhandled exception into a ProblemDetails response instead of a bare 500. Finally, UseExceptionless() adds the Exceptionless middleware, which also reports requests that end in a 404.

Older guides call builder.Services.AddExceptionless() instead. It still compiles and still reports unhandled exceptions through ASP.NET Core’s diagnostic events, but it registers only the client and skips the exception handler.

Exceptionless in Action

Once we configure Exceptionless, it will automatically start capturing the unhandled exceptions.

Let’s add a ValuesController to the Controllers folder, with a GET method that throws an exception:

using Exceptionless;
using Microsoft.AspNetCore.Mvc;

namespace ExceptionlessDemo.Controllers;

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    [HttpGet]
    public void Get()
    {
        throw new Exception("This is a test exception");
    }
}

After that, let’s run the application and navigate to the /api/values endpoint.

The application will now throw an exception and send it to Exceptionless. We can view it in the Events section of the Exceptions dashboard:

Exceptionless Events

It displays a summary of the recent events there. Furthermore, by clicking on a particular event, we can navigate to the details of the event to see the exception details, request details, environment details, etc.:

Exceptionless Event Details

Capturing Additional Data Using Exceptionless

Additionally, there are options to capture exceptions, logs, feature usages, etc. Let’s take a look at some of these options now. Each example below is another action inside the same ValuesController.

Submit an Exception

By default, Exceptionless will only capture unhandled exceptions. However, if we wish to capture handled exceptions as well, we can do that by first calling the ToExceptionless() extension method on the exception and then the Submit() method. This will create an event builder with the exception details and submit it to Exceptionless:

[HttpGet]
[Route("manualexception")]
public void ManualException()
{
    try
    {
        throw new Exception("This is a manual test exception");
    }
    catch (Exception ex)
    {
        ex.ToExceptionless().Submit();
    }
}

If we run the application once again and navigate to the /api/values/manualexception endpoint, we can see that it sends the exception details to the Exceptionless dashboard manually. Note that this will appear in the Events section of the Exceptions dashboard similar to how it displays the automatically captured exceptions.

Submit a Log Message

We can also submit log messages to Exceptionless. For that, we can use the SubmitLog() method on the default ExceptionlessClient and pass the log message into it:

[HttpGet]
[Route("logs")]
public void Logs()
{
    ExceptionlessClient.Default.SubmitLog("Logging a message.");
}

This will send the log to Exceptionless and we can view it in the Log Messages dashboard:

Exceptionless Logs

Additionally, we can click on the log message to navigate to its details page.

Submit a Feature Usage

Similarly, for submitting a feature usage to Exceptionless, we can use the SubmitFeatureUsage() method on the default ExceptionlessClient and pass the feature name into it:

[HttpGet]
[Route("feature")]
public void Feature()
{
    ExceptionlessClient.Default.SubmitFeatureUsage("FeatureName");
}

This will capture the feature usages and it will be available in the Feature Usages dashboard:

Exceptionless Feature Usages

Furthermore, by clicking the feature event, we can navigate to its details page.

Exceptionless Dashboard Features

Now let’s check some of the core capabilities available in the Exceptionless project dashboard. 

The Stacks

In Exceptionless, we can use the concept of Stacks to aggregate and organize similar errors or events. A stack represents a group of errors or events that are essentially the same, allowing us to manage those as a single entity. This aggregation helps us to efficiently manage and analyze errors and events. Stacks aggregate similar errors or events based on certain attributes like the type of the exception, the area in the code where it occurred, etc.

In the Exceptions dashboard, we can see the Stacks tiles along with the history and most frequent stacks:

Exceptionless stacks in dashboard

By clicking on a stack, we can view the detailed stacking information:

Stack details for exceptions

This can be helpful if we need to isolate certain types of exceptions or events or the ones occurring in certain areas of the applications. We could even change the status of a stack by clicking on the Status dropdown and changing it. For instance, once we identify and fix an error in the application, we could mark the related stack as fixed.

Apart from these, it is possible to create manual stacks as well.

We could set a manual stacking key for an exception:

[HttpGet]
[Route("customstack")]
public void CustomStack()
{
    try
    {
        throw new ApplicationException("Unable to create new user.");
    }
    catch (Exception ex)
    {
        ex.ToExceptionless().SetManualStackingKey("UserCreationError").Submit();
    }
}

Now all exceptions happening in this method will be stacked together. Similarly, we could stack exceptions from multiple areas together by providing the same stacking key.

Filtering and Searching

Exceptionless offers powerful filtering and searching capabilities that help us manage and understand the data efficiently. Furthermore, it has an advanced query syntax that allows filtering events by type, message, date ranges, tags, etc. We can also organize exceptions by stacks and filter them by project, organization, user, status, environment, etc. All these can be done for different types of events such as exceptions, logs, feature usages, etc.

Additionally, we can use the search option to search across a large set of fields such as source, level, message, browser, operating system, user, etc. While performing searches, for some fields such as ID, we need to prefix the field name (eg. id:). However, for other fields such as error.Message, we just need to provide the search string (eg. Object reference not set to an instance of an object). The complete list of Searchable Fields & Requirements is documented on the website.

On the hosted service, searching is one of the premium features, so it needs a paid plan.

We can also add multiple queries using AND and OR operators, perform wildcard searches using *, and exclude matching events by prefixing a field with -. We can even do range searches on date and numeric fields using <,>,=, etc.

Data Exclusions

Data exclusions in Exceptionless give us more control over the exception and log data sent to the server. This is crucial for maintaining user privacy and complying with regulations such as the General Data Protection Regulation (GDPR). By defining data exclusions, we can stop fields that hold sensitive information like passwords, credit card numbers or personal identification data from being captured, by their names or by custom-defined patterns.

Exceptionless offers a way to specify these exclusions through field identification within the project configuration, either through the portal or code. When an event is reported, the client library will scan the data for any fields that match the exclusion rules. If a match is found, the information is removed before the event is sent to the Exceptionless servers. We can specify field names or field name patterns that often contain sensitive data, such as password, token, or SSN, and those fields will be removed from the data payload.

Data exclusions let us use Exceptionless to track errors and events with less risk of exposing sensitive data. We can set data exclusion rules in the Settings tab on the Manage Project page:

Exceptionless data exclusions

There is an option to automatically remove user-identifiable information such as machine names, user details and IP addresses, and we can enable that if we need it.

We can also configure data exclusion in the code:

[HttpGet]
[Route("dataexclusion")]
public void DataExclusion()
{
    ExceptionlessClient.Default.Configuration.AddDataExclusions("password", "*email*");

    try
    {
        throw new ApplicationException("Unable to create new user.");
    }
    catch (Exception ex)
    {
        ex.ToExceptionless()
            .AddObject(new { User = "user1", Password = "password", UserEmail = "[email protected]" })
            .Submit();
    }
}

Here, we configure to exclude any field with the name password or containing the word email in it. In this example, we are logging additional data like user, password, and email along with the exception. However, with the data exclusion policy in place, it automatically excludes Password and UserEmail, recording only the User:

Exceptionless extended data showing only the User field after data exclusions

Of course, if we remove the data exclusion configuration, it will log all these fields into the Extended Data section.

Notifications

It is possible to configure email notifications for the events in Exceptionless. We can configure that in the Notifications tab in the My Account section:

Exceptionless Notifications Settings

We can configure email notifications and daily project summaries as well. Notifications for individual occurrences, such as new errors or critical errors, need a paid plan. The free plan sends daily summaries only.

Log Levels

Exceptionless supports various log levels which helps us to categorize log messages based on the severity. The log levels help in filtering and prioritizing log data, making it easier to manage and respond to the most critical issues first.

The different log levels are:

  • Trace – Low-level debugging and tracing code execution
  • Debug – Debugging the flow of applications
  • Info – Informational messages
  • Warn – Warning messages
  • Error – Errors that cause the application to fail, but are recoverable
  • Fatal – Very severe errors that could break the application

To configure different log levels, we can specify the level parameter while calling the SubmitLog() method:

[HttpGet]
[Route("loglevel")]
public void LogLevel()
{
    ExceptionlessClient.Default.SubmitLog(
        "Your log message here", 
        Exceptionless.Logging.LogLevel.Trace);
}

We also need to change the Default Log Level to Trace in the Settings tab of Manage Project for capturing trace level logs:

Default log level

The client applies this setting before anything leaves our application. When it has no project setting to go on, it drops log events below Warn, which is why a Trace message never reaches the dashboard until we change the default.

This will capture the logs with a severity level of Trace or higher:

Exceptionless trace level log

We can also integrate Exceptionless with logging frameworks like NLog, Serilog, or log4net.

By leveraging the log levels and integrating with logging frameworks, we can effectively manage the volume and priority of log data sent to Exceptionless, ensuring that we focus on the most critical information for the application’s health and diagnostics.

Integrations

Exceptionless offers seamless integration with popular tools like Zapier, Slack, and webhooks, which we can use to enhance its capabilities. We can access these integrations through the Integrations tab located in the Manage Project section of the Exceptionless dashboard. 

Like searching, these integrations are premium features on the hosted service.

How Do We Test Exceptionless Without Sending Events?

To test Exceptionless offline, we hook into the client’s SubmittingEvent event, which fires for every event the client is about to queue. The handler sees the finished event, with the exception, the request details and any extended data, and it can set Cancel to true so the event never leaves the process.

That gives us a cheap integration test for the whole setup. We start the application in memory with WebApplicationFactory, call the endpoint that throws, and check that Exceptionless built an error event for it. Nothing reaches a server, so the test needs no account and no network.

The client still has to accept its configuration. It ignores events until the API key is at least 10 characters long with no spaces, so the test sets a fake key. It also points ServerUrl at a local port where nothing listens, as a second safety net.

Let’s add the test to an xUnit Tests project, which references the web project and the Microsoft.AspNetCore.Mvc.Testing package:

using System.Net;
using Exceptionless;
using Exceptionless.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;

namespace Tests;

public class ExceptionlessCaptureTest : IClassFixture<WebApplicationFactory<Program>>
{
    private readonly WebApplicationFactory<Program> _factory;

    public ExceptionlessCaptureTest(WebApplicationFactory<Program> factory)
    {
        _factory = factory.WithWebHostBuilder(builder =>
        {
            builder.UseSetting("Exceptionless:ApiKey", "LOCAL_TEST_KEY_NOT_REAL");
            builder.UseSetting("Exceptionless:ServerUrl", "http://localhost:9");
        });
    }

    [Fact]
    public async Task GivenGetEndpoint_WhenItThrows_ThenExceptionlessCapturesAnErrorEvent()
    {
        var captured = new List<Event>();
        EventHandler<EventSubmittingEventArgs> handler = (_, e) =>
        {
            captured.Add(e.Event);
            e.Cancel = true;
        };

        ExceptionlessClient.Default.SubmittingEvent += handler;
        try
        {
            var client = _factory.CreateClient();
            var response = await client.GetAsync("/api/values");

            Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
            Assert.Contains(captured, e => e.Type == Event.KnownTypes.Error);
        }
        finally
        {
            ExceptionlessClient.Default.SubmittingEvent -= handler;
        }
    }
}

When the controller throws, the Exceptionless exception handler builds the error event, our handler stores it and cancels it, and UseExceptionHandler() answers with a 500. The handler is removed in finally because ExceptionlessClient.Default is shared by every test in the run.

The same trick works for every endpoint in this article. When we pointed it at /api/values/dataexclusion, the captured event’s extended data held only {"User":"user1"}, so the data exclusions had done their work before anything was sent. If WebApplicationFactory is new to us, our article on integration testing in ASP.NET Core covers it step by step.

Conclusion

In this article, we talked about the Exceptionless library and discussed how to integrate it into ASP.NET Core applications. Additionally, we looked at how to submit exceptions, logs, and feature usage manually, and how to test the whole setup without sending a single event.

Tested with .NET 11 (SDK 11.0.100, runtime 11.0.0), Exceptionless.AspNetCore 6.2.0 and xUnit 2.9.3.