Skip to content

Commit

Permalink
Add middleware to log unhandled exceptions to various targets (#33)
Browse files Browse the repository at this point in the history
## Description
This is the minimal functionality that I require for the moment in an ASP.NET API.   This functionality allows to log exceptions to multiple targets.
It surely needs to be extended to allow to add correlation-id's or other (custom) information.

## Documentation

I don't know what we're doing regarding documentation ?  
Anyway, usage of this middleware:

In `Startup.Configure` , this middleware can be added to the pipeline:

```csharp
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
   app.UseMiddleware<Arcus.WebApi.Logging.ExceptionHandlingMiddleware>();
}
```
The above statement will make sure that all unhandled exceptions are logged to all configured loggers.
To get the exceptions logged in AppInsights, logging should be configured like this when configuring the `IWebHost` (in Program.cs):

```csharp
WebHost.CreateDefaultBuilder(args)
              .UseApplicationInsights()
              .ConfigureLogging(loggers => loggers.AddApplicationInsights())
              .UseStartup<Startup>();
```

To be able to use the `AddApplicationInsights` extension method, the `Microsoft.Extensions.Logging.ApplicationInsights` package must be installed.

If the parameter-less `AddApplicationInsights` method is used, the configurationsetting `ApplicationInsights:TelemetryKey` must be specified and the value of the telemetry-key of the ApplicationInsights resource must be set.

#14
  • Loading branch information
fgheysels authored and tomkerkhove committed Apr 17, 2019
1 parent c4e0f5a commit 1c7f459
Show file tree
Hide file tree
Showing 3 changed files with 96 additions and 1 deletion.
24 changes: 24 additions & 0 deletions src/Arcus.WebApi.Logging/Arcus.WebApi.Logging.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<Authors>Arcus</Authors>
<Company>Arcus</Company>
<RepositoryType>Git</RepositoryType>
<PackageTags>Azure;WebAPI;App Services;Web App;Web;API</PackageTags>
<Description>Provides capabilities for easily integrating logging when building Web APIs running in Azure.</Description>
<Copyright>Copyright (c) Arcus</Copyright>
<PackageLicenseUrl>https://github.com/arcus-azure/arcus.webapi/blob/master/LICENSE</PackageLicenseUrl>
<PackageProjectUrl>https://github.com/arcus-azure/arcus.webapi</PackageProjectUrl>
<RepositoryUrl>https://github.com/arcus-azure/arcus.webapi</RepositoryUrl>
<PackageIconUrl>https://raw.githubusercontent.com/arcus-azure/arcus/master/media/arcus.png</PackageIconUrl>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.2.2" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="2.2.0" />
</ItemGroup>

</Project>
65 changes: 65 additions & 0 deletions src/Arcus.WebApi.Logging/ExceptionHandlingMiddleware.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
using System;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace Arcus.WebApi.Logging
{
public class ExceptionHandlingMiddleware
{
private readonly RequestDelegate _next;
private readonly Func<string> _getLoggingCategory;

/// <summary>
/// Initializes a new instance of the <see cref="ExceptionHandlingMiddleware"/> class.
/// </summary>
/// <param name="next"></param>
public ExceptionHandlingMiddleware(RequestDelegate next)
: this(next, string.Empty)
{ }

/// <summary>
/// Initializes a new instance of the <see cref="ExceptionHandlingMiddleware"/> class.
/// </summary>
/// <param name="next"></param>
/// <param name="categoryName">The category-name for messages produced by the logger.</param>
public ExceptionHandlingMiddleware(RequestDelegate next, string categoryName)
: this(next, () => categoryName)
{ }

/// <summary>
/// Initializes a new instance of the <see cref="ExceptionHandlingMiddleware"/> class.
/// </summary>
/// <param name="next"></param>
/// <param name="getLoggingCategory">The function that returns the category-name that must be used by the logger
/// when writing log messages.</param>
public ExceptionHandlingMiddleware(RequestDelegate next, Func<string> getLoggingCategory)
{
_next = next;
_getLoggingCategory = getLoggingCategory;
}

public async Task Invoke(HttpContext context, ILoggerFactory loggerFactory)
{
try
{
await _next(context);
}
catch (Exception ex)
{
HandleException(context, ex, loggerFactory);
}
}

private void HandleException(HttpContext context, Exception ex, ILoggerFactory loggerFactory)
{
string categoryName = _getLoggingCategory() ?? string.Empty;

var logger = loggerFactory.CreateLogger(categoryName);
logger.LogCritical(ex, ex.Message);

context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
}
}
}
8 changes: 7 additions & 1 deletion src/Arcus.WebApi.sln
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.28010.2036
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Arcus.WebApi.All", "Arcus.WebApi.All\Arcus.WebApi.All.csproj", "{19B02A8B-2E0C-44B6-A086-88FE2091D27C}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Arcus.WebApi.All", "Arcus.WebApi.All\Arcus.WebApi.All.csproj", "{19B02A8B-2E0C-44B6-A086-88FE2091D27C}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Arcus.WebApi.Logging", "Arcus.WebApi.Logging\Arcus.WebApi.Logging.csproj", "{1112242E-FD86-4531-90A3-94B37D0131DA}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Expand All @@ -15,6 +17,10 @@ Global
{19B02A8B-2E0C-44B6-A086-88FE2091D27C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{19B02A8B-2E0C-44B6-A086-88FE2091D27C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{19B02A8B-2E0C-44B6-A086-88FE2091D27C}.Release|Any CPU.Build.0 = Release|Any CPU
{1112242E-FD86-4531-90A3-94B37D0131DA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1112242E-FD86-4531-90A3-94B37D0131DA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1112242E-FD86-4531-90A3-94B37D0131DA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1112242E-FD86-4531-90A3-94B37D0131DA}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down

0 comments on commit 1c7f459

Please sign in to comment.