Skip to content

Commit

Permalink
changing string parameter for IOcelotLogger function to Func<string>,…
Browse files Browse the repository at this point in the history
… modifying asp dot net logger, only one main method and verifying if LogLevel is enabled. If log level isn't enabled, then return.
  • Loading branch information
ggnaegi committed Oct 18, 2023
1 parent 3b776a7 commit 847dac7
Show file tree
Hide file tree
Showing 48 changed files with 226 additions and 231 deletions.
2 changes: 1 addition & 1 deletion src/Ocelot.Provider.Consul/Consul.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public async Task<List<Service>> GetAsync()
else
{
_logger.LogWarning(
$"Unable to use service address: '{service.Address}' and port: {service.Port} as it is invalid for the service: '{service.Service}'. Address must contain host only e.g. 'localhost', and port must be greater than 0.");
() => $"Unable to use service address: '{service.Address}' and port: {service.Port} as it is invalid for the service: '{service.Service}'. Address must contain host only e.g. 'localhost', and port must be greater than 0.");
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/Ocelot.Provider.Consul/PollConsul.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public Task<List<Service>> GetAsync()

try
{
_logger.LogInformation($"Retrieving new client information for service: {ServiceName}...");
_logger.LogInformation(() => $"Retrieving new client information for service: {ServiceName}...");
_services = _consulServiceDiscoveryProvider.GetAsync().Result;
return Task.FromResult(_services);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public async Task<List<Service>> GetAsync()
}
else
{
_logger.LogWarning($"namespace:{_kubeRegistryConfiguration.KubeNamespace}service:{_kubeRegistryConfiguration.KeyOfServiceInK8s} Unable to use ,it is invalid. Address must contain host only e.g. localhost and port must be greater than 0");
_logger.LogWarning(() => $"namespace:{_kubeRegistryConfiguration.KubeNamespace}service:{_kubeRegistryConfiguration.KeyOfServiceInK8s} Unable to use ,it is invalid. Address must contain host only e.g. localhost and port must be greater than 0");
}

return services;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,12 @@ protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage
}
catch (BrokenCircuitException ex)
{
_logger.LogError("Reached to allowed number of exceptions. Circuit is open", ex);
_logger.LogError(() => "Reached to allowed number of exceptions. Circuit is open", ex);
throw;
}
catch (HttpRequestException ex)
{
_logger.LogError($"Error in {nameof(PollyCircuitBreakingDelegatingHandler)}.{nameof(SendAsync)}", ex);
_logger.LogError(() => $"Error in {nameof(PollyCircuitBreakingDelegatingHandler)}.{nameof(SendAsync)}", ex);
throw;
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/Ocelot.Provider.Polly/PollyQoSProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,11 @@ public PollyQoSProvider(DownstreamRoute route, IOcelotLoggerFactory loggerFactor
exceptionsAllowedBeforeBreaking: route.QosOptions.ExceptionsAllowedBeforeBreaking,
durationOfBreak: TimeSpan.FromMilliseconds(route.QosOptions.DurationOfBreak),
onBreak: (ex, breakDelay) =>
logger.LogError(info + $"Breaking the circuit for {breakDelay.TotalMilliseconds} ms!", ex),
logger.LogError(() => $"{info}Breaking the circuit for {breakDelay.TotalMilliseconds} ms!", ex),
onReset: () =>
logger.LogDebug(info + "Call OK! Closed the circuit again."),
logger.LogDebug(() => $"{info}Call OK! Closed the circuit again."),
onHalfOpen: () =>
logger.LogDebug(info + "Half-open; Next call is a trial.")
logger.LogDebug(() => $"{info}Half-open; Next call is a trial.")
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,30 +23,30 @@ public async Task Invoke(HttpContext httpContext)

if (httpContext.Request.Method.ToUpper() != "OPTIONS" && IsAuthenticatedRoute(downstreamRoute))
{
Logger.LogInformation($"{httpContext.Request.Path} is an authenticated route. {MiddlewareName} checking if client is authenticated");
Logger.LogInformation(() => $"{httpContext.Request.Path} is an authenticated route. {MiddlewareName} checking if client is authenticated");

var result = await httpContext.AuthenticateAsync(downstreamRoute.AuthenticationOptions.AuthenticationProviderKey);

httpContext.User = result.Principal;

if (httpContext.User.Identity.IsAuthenticated)
{
Logger.LogInformation($"Client has been authenticated for {httpContext.Request.Path}");
Logger.LogInformation(() => $"Client has been authenticated for {httpContext.Request.Path}");
await _next.Invoke(httpContext);
}
else
{
var error = new UnauthenticatedError(
$"Request for authenticated route {httpContext.Request.Path} by {httpContext.User.Identity.Name} was unauthenticated");

Logger.LogWarning($"Client has NOT been authenticated for {httpContext.Request.Path} and pipeline error set. {error}");
Logger.LogWarning(() =>$"Client has NOT been authenticated for {httpContext.Request.Path} and pipeline error set. {error}");

httpContext.Items.SetError(error);
}
}
else
{
Logger.LogInformation($"No authentication needed for {httpContext.Request.Path}");
Logger.LogInformation(() => $"No authentication needed for {httpContext.Request.Path}");

await _next.Invoke(httpContext);
}
Expand Down
18 changes: 9 additions & 9 deletions src/Ocelot/Authorization/Middleware/AuthorizationMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,25 +29,25 @@ public async Task Invoke(HttpContext httpContext)

if (!IsOptionsHttpMethod(httpContext) && IsAuthenticatedRoute(downstreamRoute))
{
Logger.LogInformation("route is authenticated scopes must be checked");
Logger.LogInformation(() =>"route is authenticated scopes must be checked");

var authorized = _scopesAuthorizer.Authorize(httpContext.User, downstreamRoute.AuthenticationOptions.AllowedScopes);

if (authorized.IsError)
{
Logger.LogWarning("error authorizing user scopes");
Logger.LogWarning(() => "error authorizing user scopes");

httpContext.Items.UpsertErrors(authorized.Errors);
return;
}

if (IsAuthorized(authorized))
{
Logger.LogInformation("user scopes is authorized calling next authorization checks");
Logger.LogInformation(() => "user scopes is authorized calling next authorization checks");
}
else
{
Logger.LogWarning("user scopes is not authorized setting pipeline error");
Logger.LogWarning(() =>"user scopes is not authorized setting pipeline error");

httpContext.Items.SetError(new UnauthorizedError(
$"{httpContext.User.Identity.Name} unable to access {downstreamRoute.UpstreamPathTemplate.OriginalValue}"));
Expand All @@ -56,33 +56,33 @@ public async Task Invoke(HttpContext httpContext)

if (!IsOptionsHttpMethod(httpContext) && IsAuthorizedRoute(downstreamRoute))
{
Logger.LogInformation("route is authorized");
Logger.LogInformation(() => "route is authorized");

var authorized = _claimsAuthorizer.Authorize(httpContext.User, downstreamRoute.RouteClaimsRequirement, httpContext.Items.TemplatePlaceholderNameAndValues());

if (authorized.IsError)
{
Logger.LogWarning($"Error whilst authorizing {httpContext.User.Identity.Name}. Setting pipeline error");
Logger.LogWarning(() => $"Error whilst authorizing {httpContext.User.Identity.Name}. Setting pipeline error");

httpContext.Items.UpsertErrors(authorized.Errors);
return;
}

if (IsAuthorized(authorized))
{
Logger.LogInformation($"{httpContext.User.Identity.Name} has succesfully been authorized for {downstreamRoute.UpstreamPathTemplate.OriginalValue}.");
Logger.LogInformation(() => $"{httpContext.User.Identity.Name} has succesfully been authorized for {downstreamRoute.UpstreamPathTemplate.OriginalValue}.");
await _next.Invoke(httpContext);
}
else
{
Logger.LogWarning($"{httpContext.User.Identity.Name} is not authorized to access {downstreamRoute.UpstreamPathTemplate.OriginalValue}. Setting pipeline error");
Logger.LogWarning(() => $"{httpContext.User.Identity.Name} is not authorized to access {downstreamRoute.UpstreamPathTemplate.OriginalValue}. Setting pipeline error");

httpContext.Items.SetError(new UnauthorizedError($"{httpContext.User.Identity.Name} is not authorized to access {downstreamRoute.UpstreamPathTemplate.OriginalValue}"));
}
}
else
{
Logger.LogInformation($"{downstreamRoute.DownstreamPathTemplate.Value} route does not require user to be authorized");
Logger.LogInformation(() => $"{downstreamRoute.DownstreamPathTemplate.Value} route does not require user to be authorized");
await _next.Invoke(httpContext);
}
}
Expand Down
12 changes: 6 additions & 6 deletions src/Ocelot/Cache/Middleware/OutputCacheMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,29 +35,29 @@ public async Task Invoke(HttpContext httpContext)
var downstreamUrlKey = $"{downstreamRequest.Method}-{downstreamRequest.OriginalString}";
var downStreamRequestCacheKey = _cacheGenerator.GenerateRequestCacheKey(downstreamRequest);

Logger.LogDebug($"Started checking cache for the '{downstreamUrlKey}' key.");
Logger.LogDebug(() => $"Started checking cache for the '{downstreamUrlKey}' key.");

var cached = _outputCache.Get(downStreamRequestCacheKey, downstreamRoute.CacheOptions.Region);

if (cached != null)
{
Logger.LogDebug($"Cache entry exists for the '{downstreamUrlKey}' key.");
Logger.LogDebug(() => $"Cache entry exists for the '{downstreamUrlKey}' key.");

var response = CreateHttpResponseMessage(cached);
SetHttpResponseMessageThisRequest(httpContext, response);

Logger.LogDebug($"Finished returning of cached response for the '{downstreamUrlKey}' key.");
Logger.LogDebug(() => $"Finished returning of cached response for the '{downstreamUrlKey}' key.");

return;
}

Logger.LogDebug($"No response cached for the '{downstreamUrlKey}' key.");
Logger.LogDebug(() => $"No response cached for the '{downstreamUrlKey}' key.");

await _next.Invoke(httpContext);

if (httpContext.Items.Errors().Count > 0)
{
Logger.LogDebug($"There was a pipeline error for the '{downstreamUrlKey}' key.");
Logger.LogDebug(() => $"There was a pipeline error for the '{downstreamUrlKey}' key.");

return;
}
Expand All @@ -68,7 +68,7 @@ public async Task Invoke(HttpContext httpContext)

_outputCache.Add(downStreamRequestCacheKey, cached, TimeSpan.FromSeconds(downstreamRoute.CacheOptions.TtlSeconds), downstreamRoute.CacheOptions.Region);

Logger.LogDebug($"Finished response added to cache for the '{downstreamUrlKey}' key.");
Logger.LogDebug(() => $"Finished response added to cache for the '{downstreamUrlKey}' key.");
}

private static void SetHttpResponseMessageThisRequest(HttpContext context,
Expand Down
4 changes: 2 additions & 2 deletions src/Ocelot/Claims/Middleware/ClaimsToClaimsMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,13 @@ public async Task Invoke(HttpContext httpContext)

if (downstreamRoute.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");

var result = _addClaimsToRequest.SetClaimsOnContext(downstreamRoute.ClaimsToClaims, httpContext);

if (result.IsError)
{
Logger.LogDebug("error converting claims to other claims, setting pipeline error");
Logger.LogDebug(() => "error converting claims to other claims, setting pipeline error");

httpContext.Items.UpsertErrors(result.Errors);
return;
Expand Down
2 changes: 1 addition & 1 deletion src/Ocelot/Configuration/Creator/ClaimsToThingCreator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public List<ClaimToThing> Create(Dictionary<string, string> inputToBeParsed)

if (claimToThing.IsError)
{
_logger.LogDebug($"Unable to extract configuration for key: {input.Key} and value: {input.Value} your configuration file is incorrect");
_logger.LogDebug(() => $"Unable to extract configuration for key: {input.Key} and value: {input.Value} your configuration file is incorrect");
}
else
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public HeaderTransformations Create(FileRoute fileRoute)
}
else
{
_logger.LogWarning($"Unable to add UpstreamHeaderTransform {input.Key}: {input.Value}");
_logger.LogWarning(() => $"Unable to add UpstreamHeaderTransform {input.Key}: {input.Value}");
}
}
else
Expand All @@ -55,7 +55,7 @@ public HeaderTransformations Create(FileRoute fileRoute)
}
else
{
_logger.LogWarning($"Unable to add DownstreamHeaderTransform {input.Key}: {input.Value}");
_logger.LogWarning(() => $"Unable to add DownstreamHeaderTransform {input.Key}: {input.Value}");
}
}
else
Expand Down
10 changes: 5 additions & 5 deletions src/Ocelot/Configuration/Repository/FileConfigurationPoller.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public FileConfigurationPoller(

public Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation($"{nameof(FileConfigurationPoller)} is starting.");
_logger.LogInformation(() => $"{nameof(FileConfigurationPoller)} is starting.");

_timer = new Timer(async x =>
{
Expand All @@ -53,7 +53,7 @@ public Task StartAsync(CancellationToken cancellationToken)

public Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation($"{nameof(FileConfigurationPoller)} is stopping.");
_logger.LogInformation(() => $"{nameof(FileConfigurationPoller)} is stopping.");

_timer?.Change(Timeout.Infinite, 0);

Expand All @@ -62,13 +62,13 @@ public Task StopAsync(CancellationToken cancellationToken)

private async Task Poll()
{
_logger.LogInformation("Started polling");
_logger.LogInformation(() => "Started polling");

var fileConfig = await _repo.Get();

if (fileConfig.IsError)
{
_logger.LogWarning($"error geting file config, errors are {string.Join(',', fileConfig.Errors.Select(x => x.Message))}");
_logger.LogWarning(() =>$"error geting file config, errors are {string.Join(',', fileConfig.Errors.Select(x => x.Message))}");
return;
}

Expand All @@ -86,7 +86,7 @@ private async Task Poll()
_previousAsJson = asJson;
}

_logger.LogInformation("Finished polling");
_logger.LogInformation(() => "Finished polling");
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public async Task Invoke(HttpContext httpContext)

if (downstreamRoute.ClaimsToPath.Any())
{
Logger.LogInformation($"{downstreamRoute.DownstreamPathTemplate.Value} has instructions to convert claims to path");
Logger.LogInformation(() => $"{downstreamRoute.DownstreamPathTemplate.Value} has instructions to convert claims to path");

var templatePlaceholderNameAndValues = httpContext.Items.TemplatePlaceholderNameAndValues();

Expand All @@ -34,7 +34,7 @@ public async Task Invoke(HttpContext httpContext)

if (response.IsError)
{
Logger.LogWarning("there was an error setting queries on context, setting pipeline error");
Logger.LogWarning(() => "there was an error setting queries on context, setting pipeline error");

httpContext.Items.UpsertErrors(response.Errors);
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public IDownstreamRouteProvider Get(IInternalConfiguration config)
//an upstream path template which means they are dyanmic and service discovery is on...
if ((!config.Routes.Any() || config.Routes.All(x => string.IsNullOrEmpty(x.UpstreamTemplatePattern?.OriginalValue))) && IsServiceDiscovery(config.ServiceProviderConfiguration))
{
_logger.LogInformation($"Selected {nameof(DownstreamRouteCreator)} as DownstreamRouteProvider for this request");
_logger.LogInformation(() => $"Selected {nameof(DownstreamRouteCreator)} as DownstreamRouteProvider for this request");
return _providers[nameof(DownstreamRouteCreator)];
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public async Task Invoke(HttpContext httpContext)
? hostHeader.Split(':')[0]
: hostHeader;

Logger.LogDebug($"Upstream url path is {upstreamUrlPath}");
Logger.LogDebug(() => $"Upstream url path is {upstreamUrlPath}");

var internalConfiguration = httpContext.Items.IInternalConfiguration();

Expand All @@ -42,14 +42,17 @@ public async Task Invoke(HttpContext httpContext)

if (response.IsError)
{
Logger.LogWarning($"{MiddlewareName} setting pipeline errors. IDownstreamRouteFinder returned {response.Errors.ToErrorString()}");
Logger.LogWarning(() => $"{MiddlewareName} setting pipeline errors. IDownstreamRouteFinder returned {response.Errors.ToErrorString()}");

httpContext.Items.UpsertErrors(response.Errors);
return;
}

var downstreamPathTemplates = string.Join(", ", response.Data.Route.DownstreamRoute.Select(r => r.DownstreamPathTemplate.Value));
Logger.LogDebug($"downstream templates are {downstreamPathTemplates}");
Logger.LogDebug(() =>
{
var downstreamPathTemplates = string.Join(", ", response.Data.Route.DownstreamRoute.Select(r => r.DownstreamPathTemplate.Value));
return $"downstream templates are {downstreamPathTemplates}";
});

// why set both of these on HttpContext
httpContext.Items.UpsertTemplatePlaceholderNameAndValues(response.Data.TemplatePlaceholderNameAndValues);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public async Task Invoke(HttpContext httpContext)

if (response.IsError)
{
Logger.LogDebug("IDownstreamPathPlaceholderReplacer returned an error, setting pipeline error");
Logger.LogDebug(() => "IDownstreamPathPlaceholderReplacer returned an error, setting pipeline error");

httpContext.Items.UpsertErrors(response.Errors);
return;
Expand Down Expand Up @@ -85,7 +85,7 @@ public async Task Invoke(HttpContext httpContext)
}
}

Logger.LogDebug($"Downstream url is {downstreamRequest}");
Logger.LogDebug(() =>$"Downstream url is {downstreamRequest}");

await _next.Invoke(httpContext);
}
Expand Down
Loading

0 comments on commit 847dac7

Please sign in to comment.