-
Notifications
You must be signed in to change notification settings - Fork 12
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add middleware to log unhandled exceptions to various targets (#33)
## 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
1 parent
c4e0f5a
commit 1c7f459
Showing
3 changed files
with
96 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters