NDB.Logging.Api -> RequestLoggingConfiguration

messaging
Tudor Stanciu 2019-11-05 12:43:44 +02:00
parent 4f986fbab8
commit 1cd3a9611c
3 changed files with 21 additions and 3 deletions

View File

@ -1,4 +1,5 @@
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using NDB.Logging.Api.Entities;
namespace NDB.Logging.Api namespace NDB.Logging.Api
{ {
@ -6,6 +7,13 @@ namespace NDB.Logging.Api
{ {
public static void AddRequestLogging(this IServiceCollection services) public static void AddRequestLogging(this IServiceCollection services)
{ {
services.AddSingleton(new RequestLoggingConfiguration() { LogBody = false });
services.AddScoped<RequestLoggingAttribute>();
}
public static void AddRequestLogging(this IServiceCollection services, bool logBody)
{
services.AddSingleton(new RequestLoggingConfiguration() { LogBody = logBody });
services.AddScoped<RequestLoggingAttribute>(); services.AddScoped<RequestLoggingAttribute>();
} }
} }

View File

@ -0,0 +1,7 @@
namespace NDB.Logging.Api.Entities
{
public class RequestLoggingConfiguration
{
public bool LogBody { get; set; }
}
}

View File

@ -2,6 +2,7 @@
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using NDB.Logging.Api.Entities;
using System; using System;
using System.Diagnostics; using System.Diagnostics;
using System.IO; using System.IO;
@ -13,10 +14,12 @@ namespace NDB.Logging.Api
public class RequestLoggingAttribute : ActionFilterAttribute public class RequestLoggingAttribute : ActionFilterAttribute
{ {
private readonly ILogger<RequestLoggingAttribute> _logger; private readonly ILogger<RequestLoggingAttribute> _logger;
private readonly RequestLoggingConfiguration _requestLoggingConfiguration;
public RequestLoggingAttribute(ILogger<RequestLoggingAttribute> logger) public RequestLoggingAttribute(ILogger<RequestLoggingAttribute> logger, RequestLoggingConfiguration requestLoggingConfiguration)
{ {
_logger = logger; _logger = logger;
_requestLoggingConfiguration = requestLoggingConfiguration;
} }
public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
@ -33,7 +36,7 @@ namespace NDB.Logging.Api
var logContent = $"Start request {uid} for method {requestUrl}"; var logContent = $"Start request {uid} for method {requestUrl}";
if (request.Method == WebRequestMethods.Http.Post) if (_requestLoggingConfiguration.LogBody && request.Method == WebRequestMethods.Http.Post)
{ {
var requestBody = await GetRequestBody(request); var requestBody = await GetRequestBody(request);
logContent += $" with body {requestBody}"; logContent += $" with body {requestBody}";