Use DiagnosticListner for middleware logging

Instead of each middleware having to log that it has started and ended,
the DianosticListner package allows for capturing of these events in a
lightwieght manner.

This commit implements this and removes unncessary logging from most
middleware.
This commit is contained in:
Marc Denman 2017-04-17 11:23:34 +01:00
parent 8d31b40c21
commit 637d93dc4b
16 changed files with 98 additions and 125 deletions

View File

@ -34,8 +34,6 @@ namespace Ocelot.Authentication.Middleware
public async Task Invoke(HttpContext context) public async Task Invoke(HttpContext context)
{ {
_logger.TraceMiddlewareEntry();
if (IsAuthenticatedRoute(DownstreamRoute.ReRoute)) if (IsAuthenticatedRoute(DownstreamRoute.ReRoute))
{ {
_logger.LogDebug($"{context.Request.Path} is an authenticated route. {MiddlwareName} checking if client is authenticated"); _logger.LogDebug($"{context.Request.Path} is an authenticated route. {MiddlwareName} checking if client is authenticated");
@ -46,7 +44,6 @@ namespace Ocelot.Authentication.Middleware
{ {
_logger.LogError($"Error getting authentication handler for {context.Request.Path}. {authenticationHandler.Errors.ToErrorString()}"); _logger.LogError($"Error getting authentication handler for {context.Request.Path}. {authenticationHandler.Errors.ToErrorString()}");
SetPipelineError(authenticationHandler.Errors); SetPipelineError(authenticationHandler.Errors);
_logger.TraceMiddlewareCompleted();
return; return;
} }
@ -56,11 +53,7 @@ namespace Ocelot.Authentication.Middleware
if (context.User.Identity.IsAuthenticated) if (context.User.Identity.IsAuthenticated)
{ {
_logger.LogDebug($"Client has been authenticated for {context.Request.Path}"); _logger.LogDebug($"Client has been authenticated for {context.Request.Path}");
_logger.TraceInvokeNext();
await _next.Invoke(context); await _next.Invoke(context);
_logger.TraceInvokeNextCompleted();
_logger.TraceMiddlewareCompleted();
} }
else else
{ {
@ -72,8 +65,6 @@ namespace Ocelot.Authentication.Middleware
_logger.LogError($"Client has NOT been authenticated for {context.Request.Path} and pipeline error set. {error.ToErrorString()}"); _logger.LogError($"Client has NOT been authenticated for {context.Request.Path} and pipeline error set. {error.ToErrorString()}");
SetPipelineError(error); SetPipelineError(error);
_logger.TraceMiddlewareCompleted();
return; return;
} }
} }
@ -81,10 +72,7 @@ namespace Ocelot.Authentication.Middleware
{ {
_logger.LogTrace($"No authentication needed for {context.Request.Path}"); _logger.LogTrace($"No authentication needed for {context.Request.Path}");
_logger.TraceInvokeNext();
await _next.Invoke(context); await _next.Invoke(context);
_logger.TraceInvokeNextCompleted();
_logger.TraceMiddlewareCompleted();
} }
} }

View File

@ -29,17 +29,15 @@ namespace Ocelot.Authorisation.Middleware
public async Task Invoke(HttpContext context) public async Task Invoke(HttpContext context)
{ {
_logger.LogDebug("started authorisation");
if (DownstreamRoute.ReRoute.IsAuthorised) if (DownstreamRoute.ReRoute.IsAuthorised)
{ {
_logger.LogDebug("route is authorised"); _logger.LogDebug($"{DownstreamRoute.ReRoute.DownstreamPathTemplate.Value} route requires user to be authorised");
var authorised = _authoriser.Authorise(context.User, DownstreamRoute.ReRoute.RouteClaimsRequirement); var authorised = _authoriser.Authorise(context.User, DownstreamRoute.ReRoute.RouteClaimsRequirement);
if (authorised.IsError) if (authorised.IsError)
{ {
_logger.LogDebug("error authorising user"); _logger.LogDebug($"Error whilst authorising {context.User.Identity.Name} for {context.User.Identity.Name}. Setting pipeline error");
SetPipelineError(authorised.Errors); SetPipelineError(authorised.Errors);
return; return;
@ -47,30 +45,23 @@ namespace Ocelot.Authorisation.Middleware
if (IsAuthorised(authorised)) if (IsAuthorised(authorised))
{ {
_logger.LogDebug("user is authorised calling next middleware"); _logger.LogDebug($"{context.User.Identity.Name} has succesfully been authorised for {DownstreamRoute.ReRoute.UpstreamPathTemplate.Value}. Calling next middleware");
await _next.Invoke(context); await _next.Invoke(context);
_logger.LogDebug("succesfully called next middleware");
} }
else else
{ {
_logger.LogDebug("user is not authorised setting pipeline error"); _logger.LogDebug($"{context.User.Identity.Name} is not authorised to access {DownstreamRoute.ReRoute.UpstreamPathTemplate.Value}. Setting pipeline error");
SetPipelineError(new List<Error> SetPipelineError(new List<Error>
{ {
new UnauthorisedError( new UnauthorisedError($"{context.User.Identity.Name} is not authorised to access {DownstreamRoute.ReRoute.UpstreamPathTemplate.Value}")
$"{context.User.Identity.Name} unable to access {DownstreamRoute.ReRoute.UpstreamPathTemplate.Value}")
}); });
} }
} }
else else
{ {
_logger.LogDebug("AuthorisationMiddleware.Invoke route is not authorised calling next middleware"); _logger.LogDebug($"{DownstreamRoute.ReRoute.DownstreamPathTemplate.Value} route does not require user to be authorised");
await _next.Invoke(context); await _next.Invoke(context);
_logger.LogDebug("succesfully called next middleware");
} }
} }

View File

@ -54,8 +54,6 @@ namespace Ocelot.Cache.Middleware
await _next.Invoke(context); await _next.Invoke(context);
_logger.LogDebug("succesfully called next middleware");
if (PipelineError) if (PipelineError)
{ {
_logger.LogDebug("there was a pipeline error for {downstreamUrlKey}", downstreamUrlKey); _logger.LogDebug("there was a pipeline error for {downstreamUrlKey}", downstreamUrlKey);

View File

@ -26,8 +26,6 @@ namespace Ocelot.Claims.Middleware
public async Task Invoke(HttpContext context) public async Task Invoke(HttpContext context)
{ {
_logger.LogDebug("started claims middleware");
if (DownstreamRoute.ReRoute.ClaimsToClaims.Any()) if (DownstreamRoute.ReRoute.ClaimsToClaims.Any())
{ {
_logger.LogDebug("this route has instructions to convert claims to other claims"); _logger.LogDebug("this route has instructions to convert claims to other claims");
@ -42,12 +40,7 @@ namespace Ocelot.Claims.Middleware
return; return;
} }
} }
_logger.LogDebug("calling next middleware");
await _next.Invoke(context); await _next.Invoke(context);
_logger.LogDebug("succesfully called next middleware");
} }
} }
} }

View File

@ -166,6 +166,11 @@ namespace Ocelot.DependencyInjection
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>(); services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.TryAddScoped<IRequestScopedDataRepository, HttpDataRepository>(); services.TryAddScoped<IRequestScopedDataRepository, HttpDataRepository>();
services.AddMemoryCache(); services.AddMemoryCache();
//Used to log the the start and ending of middleware
services.TryAddSingleton<OcelotDiagnosticListener>();
services.AddMiddlewareAnalysis();
return services; return services;
} }
} }

View File

@ -30,8 +30,6 @@ namespace Ocelot.DownstreamRouteFinder.Middleware
public async Task Invoke(HttpContext context) public async Task Invoke(HttpContext context)
{ {
_logger.TraceMiddlewareEntry();
var upstreamUrlPath = context.Request.Path.ToString().SetLastCharacterAs('/'); var upstreamUrlPath = context.Request.Path.ToString().SetLastCharacterAs('/');
_logger.LogDebug("upstream url path is {upstreamUrlPath}", upstreamUrlPath); _logger.LogDebug("upstream url path is {upstreamUrlPath}", upstreamUrlPath);
@ -43,8 +41,6 @@ namespace Ocelot.DownstreamRouteFinder.Middleware
_logger.LogError($"{MiddlwareName} setting pipeline errors. IDownstreamRouteFinder returned {downstreamRoute.Errors.ToErrorString()}"); _logger.LogError($"{MiddlwareName} setting pipeline errors. IDownstreamRouteFinder returned {downstreamRoute.Errors.ToErrorString()}");
SetPipelineError(downstreamRoute.Errors); SetPipelineError(downstreamRoute.Errors);
_logger.TraceMiddlewareCompleted();
return; return;
} }
@ -52,12 +48,7 @@ namespace Ocelot.DownstreamRouteFinder.Middleware
SetDownstreamRouteForThisRequest(downstreamRoute.Data); SetDownstreamRouteForThisRequest(downstreamRoute.Data);
_logger.TraceInvokeNext();
await _next.Invoke(context); await _next.Invoke(context);
_logger.TraceInvokeNextCompleted();
_logger.TraceMiddlewareCompleted();
} }
} }
} }

View File

@ -29,8 +29,6 @@ namespace Ocelot.DownstreamUrlCreator.Middleware
public async Task Invoke(HttpContext context) public async Task Invoke(HttpContext context)
{ {
_logger.LogDebug("started calling downstream url creator middleware");
var dsPath = _replacer var dsPath = _replacer
.Replace(DownstreamRoute.ReRoute.DownstreamPathTemplate, DownstreamRoute.TemplatePlaceholderNameAndValues); .Replace(DownstreamRoute.ReRoute.DownstreamPathTemplate, DownstreamRoute.TemplatePlaceholderNameAndValues);
@ -60,11 +58,7 @@ namespace Ocelot.DownstreamUrlCreator.Middleware
SetDownstreamUrlForThisRequest(dsUrl.Data.Value); SetDownstreamUrlForThisRequest(dsUrl.Data.Value);
_logger.LogDebug("calling next middleware");
await _next.Invoke(context); await _next.Invoke(context);
_logger.LogDebug("succesfully called next middleware");
} }
} }
} }

View File

@ -26,17 +26,15 @@ namespace Ocelot.Headers.Middleware
public async Task Invoke(HttpContext context) public async Task Invoke(HttpContext context)
{ {
_logger.LogDebug("started calling headers builder middleware");
if (DownstreamRoute.ReRoute.ClaimsToHeaders.Any()) if (DownstreamRoute.ReRoute.ClaimsToHeaders.Any())
{ {
_logger.LogDebug("this route has instructions to convert claims to headers"); _logger.LogDebug($"{ DownstreamRoute.ReRoute.DownstreamPathTemplate.Value} has instructions to convert claims to headers");
var response = _addHeadersToRequest.SetHeadersOnContext(DownstreamRoute.ReRoute.ClaimsToHeaders, context); var response = _addHeadersToRequest.SetHeadersOnContext(DownstreamRoute.ReRoute.ClaimsToHeaders, context);
if (response.IsError) if (response.IsError)
{ {
_logger.LogDebug("there was an error setting headers on context, setting pipeline error"); _logger.LogDebug("Error setting headers on context, setting pipeline error");
SetPipelineError(response.Errors); SetPipelineError(response.Errors);
return; return;
@ -45,11 +43,7 @@ namespace Ocelot.Headers.Middleware
_logger.LogDebug("headers have been set on context"); _logger.LogDebug("headers have been set on context");
} }
_logger.LogDebug("calling next middleware");
await _next.Invoke(context); await _next.Invoke(context);
_logger.LogDebug("succesfully called next middleware");
} }
} }
} }

View File

@ -28,11 +28,10 @@ namespace Ocelot.LoadBalancer.Middleware
public async Task Invoke(HttpContext context) public async Task Invoke(HttpContext context)
{ {
_logger.LogDebug("started calling load balancing middleware");
var loadBalancer = _loadBalancerHouse.Get(DownstreamRoute.ReRoute.ReRouteKey); var loadBalancer = _loadBalancerHouse.Get(DownstreamRoute.ReRoute.ReRouteKey);
if(loadBalancer.IsError) if(loadBalancer.IsError)
{ {
_logger.LogDebug("there was an error retriving the loadbalancer, setting pipeline error");
SetPipelineError(loadBalancer.Errors); SetPipelineError(loadBalancer.Errors);
return; return;
} }
@ -40,29 +39,26 @@ namespace Ocelot.LoadBalancer.Middleware
var hostAndPort = await loadBalancer.Data.Lease(); var hostAndPort = await loadBalancer.Data.Lease();
if(hostAndPort.IsError) if(hostAndPort.IsError)
{ {
_logger.LogDebug("there was an error leasing the loadbalancer, setting pipeline error");
SetPipelineError(hostAndPort.Errors); SetPipelineError(hostAndPort.Errors);
return; return;
} }
SetHostAndPortForThisRequest(hostAndPort.Data); SetHostAndPortForThisRequest(hostAndPort.Data);
_logger.LogDebug("calling next middleware");
try try
{ {
await _next.Invoke(context); await _next.Invoke(context);
loadBalancer.Data.Release(hostAndPort.Data);
} }
catch (Exception) catch (Exception)
{ {
loadBalancer.Data.Release(hostAndPort.Data); _logger.LogDebug("Exception calling next middleware, exception will be thrown to global handler");
_logger.LogDebug("error calling next middleware, exception will be thrown to global handler");
throw; throw;
} }
finally
_logger.LogDebug("succesfully called next middleware"); {
loadBalancer.Data.Release(hostAndPort.Data);
}
} }
} }
} }

View File

@ -0,0 +1,27 @@
using System;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DiagnosticAdapter;
namespace Ocelot.Logging
{
public class OcelotDiagnosticListener
{
[DiagnosticName("Microsoft.AspNetCore.MiddlewareAnalysis.MiddlewareStarting")]
public virtual void OnMiddlewareStarting(HttpContext httpContext, string name)
{
Console.WriteLine($"MiddlewareStarting: {name}; {httpContext.Request.Path}");
}
[DiagnosticName("Microsoft.AspNetCore.MiddlewareAnalysis.MiddlewareException")]
public virtual void OnMiddlewareException(Exception exception, string name)
{
Console.WriteLine($"MiddlewareException: {name}; {exception.Message}");
}
[DiagnosticName("Microsoft.AspNetCore.MiddlewareAnalysis.MiddlewareFinished")]
public virtual void OnMiddlewareFinished(HttpContext httpContext, string name)
{
Console.WriteLine($"MiddlewareFinished: {name}; {httpContext.Response.StatusCode}");
}
}
}

View File

@ -1,6 +1,8 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using IdentityServer4.AccessTokenValidation; using IdentityServer4.AccessTokenValidation;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Ocelot.Authentication.Middleware; using Ocelot.Authentication.Middleware;
using Ocelot.Cache.Middleware; using Ocelot.Cache.Middleware;
using Ocelot.Claims.Middleware; using Ocelot.Claims.Middleware;
@ -8,6 +10,7 @@ using Ocelot.DownstreamRouteFinder.Middleware;
using Ocelot.DownstreamUrlCreator.Middleware; using Ocelot.DownstreamUrlCreator.Middleware;
using Ocelot.Errors.Middleware; using Ocelot.Errors.Middleware;
using Ocelot.Headers.Middleware; using Ocelot.Headers.Middleware;
using Ocelot.Logging;
using Ocelot.QueryStrings.Middleware; using Ocelot.QueryStrings.Middleware;
using Ocelot.Request.Middleware; using Ocelot.Request.Middleware;
using Ocelot.Requester.Middleware; using Ocelot.Requester.Middleware;
@ -53,6 +56,8 @@ namespace Ocelot.Middleware
{ {
await CreateAdministrationArea(builder); await CreateAdministrationArea(builder);
ConfigureDiagnosticListener(builder);
// This is registered to catch any global exceptions that are not handled // This is registered to catch any global exceptions that are not handled
builder.UseExceptionHandlerMiddleware(); builder.UseExceptionHandlerMiddleware();
@ -196,6 +201,22 @@ namespace Ocelot.Middleware
} }
} }
/// <summary>
/// Configure a DiagnosticListener to listen for diagnostic events when the middleware starts and ends
/// </summary>
/// <param name="builder"></param>
private static void ConfigureDiagnosticListener(IApplicationBuilder builder)
{
var env = builder.ApplicationServices.GetService<IHostingEnvironment>();
if (!env.IsProduction())
{
var listener = builder.ApplicationServices.GetService<OcelotDiagnosticListener>();
var diagnosticListener = builder.ApplicationServices.GetService<DiagnosticListener>();
diagnosticListener.SubscribeWithAdapter(listener);
}
}
private static void UseIfNotNull(this IApplicationBuilder builder, Func<HttpContext, Func<Task>, Task> middleware) private static void UseIfNotNull(this IApplicationBuilder builder, Func<HttpContext, Func<Task>, Task> middleware)
{ {
if (middleware != null) if (middleware != null)

View File

@ -21,10 +21,12 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.MiddlewareAnalysis" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Server.IISIntegration" Version="1.1.1" /> <PackageReference Include="Microsoft.AspNetCore.Server.IISIntegration" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="1.1.1" /> <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="1.1.1" /> <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="1.1.1" /> <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.DiagnosticAdapter" Version="1.1.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="1.1.1" /> <PackageReference Include="Microsoft.Extensions.Logging" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="1.1.1" /> <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.1" /> <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.1" />

View File

@ -26,11 +26,9 @@ namespace Ocelot.QueryStrings.Middleware
public async Task Invoke(HttpContext context) public async Task Invoke(HttpContext context)
{ {
_logger.LogDebug("started calling query string builder middleware");
if (DownstreamRoute.ReRoute.ClaimsToQueries.Any()) if (DownstreamRoute.ReRoute.ClaimsToQueries.Any())
{ {
_logger.LogDebug("this route has instructions to convert claims to queries"); _logger.LogDebug($"{DownstreamRoute.ReRoute.DownstreamPathTemplate.Value} has instructions to convert claims to queries");
var response = _addQueriesToRequest.SetQueriesOnContext(DownstreamRoute.ReRoute.ClaimsToQueries, context); var response = _addQueriesToRequest.SetQueriesOnContext(DownstreamRoute.ReRoute.ClaimsToQueries, context);
@ -43,11 +41,7 @@ namespace Ocelot.QueryStrings.Middleware
} }
} }
_logger.LogDebug("calling next middleware");
await _next.Invoke(context); await _next.Invoke(context);
_logger.LogDebug("succesfully called next middleware");
} }
} }
} }

View File

@ -31,18 +31,13 @@ namespace Ocelot.RateLimit.Middleware
public async Task Invoke(HttpContext context) public async Task Invoke(HttpContext context)
{ {
_logger.TraceMiddlewareEntry();
var options = DownstreamRoute.ReRoute.RateLimitOptions; var options = DownstreamRoute.ReRoute.RateLimitOptions;
// check if rate limiting is enabled // check if rate limiting is enabled
if (!DownstreamRoute.ReRoute.EnableEndpointEndpointRateLimiting) if (!DownstreamRoute.ReRoute.EnableEndpointEndpointRateLimiting)
{ {
_logger.LogDebug($"EndpointRateLimiting is not enabled for {DownstreamRoute.ReRoute.DownstreamPathTemplate}"); _logger.LogDebug($"EndpointRateLimiting is not enabled for {DownstreamRoute.ReRoute.DownstreamPathTemplate}");
_logger.TraceInvokeNext();
await _next.Invoke(context); await _next.Invoke(context);
_logger.TraceInvokeNextCompleted();
_logger.TraceMiddlewareCompleted();
return; return;
} }
// compute identity from request // compute identity from request
@ -52,11 +47,8 @@ namespace Ocelot.RateLimit.Middleware
if (IsWhitelisted(identity, options)) if (IsWhitelisted(identity, options))
{ {
_logger.LogDebug($"{DownstreamRoute.ReRoute.DownstreamPathTemplate} is white listed from rate limiting"); _logger.LogDebug($"{DownstreamRoute.ReRoute.DownstreamPathTemplate} is white listed from rate limiting");
_logger.TraceInvokeNext();
await _next.Invoke(context); await _next.Invoke(context);
_logger.TraceInvokeNextCompleted();
_logger.TraceMiddlewareCompleted();
return; return;
} }
@ -77,7 +69,6 @@ namespace Ocelot.RateLimit.Middleware
// break execution // break execution
await ReturnQuotaExceededResponse(context, options, retryAfter); await ReturnQuotaExceededResponse(context, options, retryAfter);
_logger.TraceMiddlewareCompleted();
return; return;
} }
} }
@ -88,10 +79,8 @@ namespace Ocelot.RateLimit.Middleware
context.Response.OnStarting(SetRateLimitHeaders, state: headers); context.Response.OnStarting(SetRateLimitHeaders, state: headers);
} }
_logger.TraceInvokeNext();
await _next.Invoke(context); await _next.Invoke(context);
_logger.TraceInvokeNextCompleted();
_logger.TraceMiddlewareCompleted();
} }
public virtual ClientRequestIdentity SetIdentity(HttpContext httpContext, RateLimitOptions option) public virtual ClientRequestIdentity SetIdentity(HttpContext httpContext, RateLimitOptions option)

View File

@ -26,16 +26,10 @@ namespace Ocelot.RequestId.Middleware
public async Task Invoke(HttpContext context) public async Task Invoke(HttpContext context)
{ {
_logger.TraceMiddlewareEntry();
SetOcelotRequestId(context); SetOcelotRequestId(context);
_logger.LogDebug("set requestId"); _logger.LogDebug("set requestId");
_logger.TraceInvokeNext();
await _next.Invoke(context); await _next.Invoke(context);
_logger.TraceInvokeNextCompleted();
_logger.TraceMiddlewareCompleted();
} }
private void SetOcelotRequestId(HttpContext context) private void SetOcelotRequestId(HttpContext context)

View File

@ -34,10 +34,7 @@ namespace Ocelot.Responder.Middleware
public async Task Invoke(HttpContext context) public async Task Invoke(HttpContext context)
{ {
_logger.TraceMiddlewareEntry();
_logger.TraceInvokeNext();
await _next.Invoke(context); await _next.Invoke(context);
_logger.TraceInvokeNextCompleted();
if (PipelineError) if (PipelineError)
{ {
@ -51,7 +48,6 @@ namespace Ocelot.Responder.Middleware
_logger.LogDebug("no pipeline errors, setting and returning completed response"); _logger.LogDebug("no pipeline errors, setting and returning completed response");
await _responder.SetResponseOnHttpContext(context, HttpResponseMessage); await _responder.SetResponseOnHttpContext(context, HttpResponseMessage);
} }
_logger.TraceMiddlewareCompleted();
} }
private void SetErrorResponse(HttpContext context, List<Error> errors) private void SetErrorResponse(HttpContext context, List<Error> errors)