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 NDB.Logging.Api.Entities;
namespace NDB.Logging.Api
{
@ -6,6 +7,13 @@ namespace NDB.Logging.Api
{
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>();
}
}

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.Filters;
using Microsoft.Extensions.Logging;
using NDB.Logging.Api.Entities;
using System;
using System.Diagnostics;
using System.IO;
@ -13,10 +14,12 @@ namespace NDB.Logging.Api
public class RequestLoggingAttribute : ActionFilterAttribute
{
private readonly ILogger<RequestLoggingAttribute> _logger;
private readonly RequestLoggingConfiguration _requestLoggingConfiguration;
public RequestLoggingAttribute(ILogger<RequestLoggingAttribute> logger)
public RequestLoggingAttribute(ILogger<RequestLoggingAttribute> logger, RequestLoggingConfiguration requestLoggingConfiguration)
{
_logger = logger;
_requestLoggingConfiguration = requestLoggingConfiguration;
}
public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
@ -33,12 +36,12 @@ namespace NDB.Logging.Api
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);
logContent += $" with body {requestBody}";
}
_logger.LogInformation(logContent);
var resultContext = await next();