-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathControllerNameLoggerGroupMiddleware.cs
45 lines (38 loc) · 1.25 KB
/
ControllerNameLoggerGroupMiddleware.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Logging;
namespace TestWebApplication
{
// Make sure you register routing (UseRouting) before this middleware or route data won't be available when it is invoked.
public class ControllerNameLoggerGroupMiddleware
{
private readonly ILogger<ControllerNameLoggerGroupMiddleware> _Logger;
private readonly RequestDelegate _Next;
public ControllerNameLoggerGroupMiddleware(ILogger<ControllerNameLoggerGroupMiddleware> logger, RequestDelegate next)
{
_Logger = logger ?? throw new ArgumentNullException(nameof(logger));
_Next = next ?? throw new ArgumentNullException(nameof(next));
}
public async Task InvokeAsync(HttpContext context)
{
RouteValueDictionary? RouteValues = context?.Request.RouteValues;
IDisposable? Group = null;
if (RouteValues != null && RouteValues.TryGetValue("controller", out object? ControllerName))
{
string? controllerName = ControllerName?.ToString();
if (!string.IsNullOrEmpty(controllerName))
Group = _Logger.BeginGroup(controllerName);
}
try
{
await _Next(context!).ConfigureAwait(false);
}
finally
{
Group?.Dispose();
}
}
}
}