繁体   English   中英

ASP.Net Core Web API 捕获用于日志记录的 HTTP 请求

[英]ASP.Net Core Web API Capturing HTTP Requests for Logging

我在 ASP.NET Core Web API 中捕获用于日志记录目的的 HTTP 请求有困难。 我在这里找到了一个例子

http://dotnetliberty.com/index.php/2016/01/07/logging-asp-net-5-requests-using-middleware/

这有帮助。 它基本上是一个使用中间件功能添加到 HTTP 请求管道的日志记录类。 问题是类方法只在应用程序启动时被调用。 我无法在我的任何 get 或 post http 请求中调用它。 get 或 post http 请求正在工作,因为我可以调试并且响应正常,我尝试在控制台应用程序中使用 Fiddler 和 http 客户端。

这是我的日志类

using Microsoft.AspNetCore.Http; 
using Microsoft.Extensions.Logging; 
using System; 
using System.Collections.Generic; 
using System.Diagnostics; 
using System.Linq; 
using System.Threading.Tasks; 


namespace CoreWebAPI.Models 
{ 
public class RequestLoggingMiddleware 
{ 
    private readonly RequestDelegate _next; 
    private readonly ILogger<RequestLoggingMiddleware> _logger; 


    public RequestLoggingMiddleware(RequestDelegate next, ILogger<RequestLoggingMiddleware> logger) 
    { 
        _next = next; 
        _logger = logger; 
    } 


    public async Task Invoke(HttpContext context) 
    { 
        var startTime = DateTime.UtcNow; 


        var watch = Stopwatch.StartNew(); 
        await _next.Invoke(context); 
        watch.Stop(); 


        var logTemplate = @" 
Client IP: {clientIP} 
Request path: {requestPath} 
Request content type: {requestContentType} 
Request content length: {requestContentLength} 
Start time: {startTime} 
Duration: {duration}"; 


        _logger.LogInformation(logTemplate, 
            context.Connection.RemoteIpAddress.ToString(), 
            context.Request.Path, 
            context.Request.ContentType, 
            context.Request.ContentLength, 
            startTime, 
            watch.ElapsedMilliseconds); 
    } 
} 
} 

这是我的 Startup.cs 类中的 Startup.Configure 方法

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
    { 
        loggerFactory.AddConsole(Configuration.GetSection("Logging")); 
        loggerFactory.AddDebug(); 




        app.UseApplicationInsightsRequestTelemetry(); 


        app.UseApplicationInsightsExceptionTelemetry(); 


        app.UseMvc(); 
        app.UseCors(builder => builder.AllowAnyOrigin()); 


        app.UseMiddleware<RequestLoggingMiddleware>(); 

    }

最后一行是我使用 app.UseMiddleware 搭载 HTTP 请求的地方。 我认为这应该可行,但如果有人知道为什么不可行或替代方案会很好。 请让我知道您是否应该提供更多信息。

中间件在某种管道中被调用,按照它们注册的顺序,它们都决定是否应该调用下一个(请参阅您自己的日志记录中间件: await _next.Invoke(context); )。

当一个由 Mvc 框架处理的请求进来时,它不会被传递到下一个中​​间件。

要获取所有请求的日志记录,您需要将日志记录的注册放在终止管道的任何中间件(例如 Mvc)之前。

这将工作得很好。

public async Task Invoke(HttpContext context)
{
    var timer = new Stopwatch();
    timer.Start();
    await _next(context);

    //Need to stop the timer after the pipeline finish
    timer.Stop();
    _logger.LogDebug("The request took '{0}' ms", timerer.ElapsedMilliseconds);
}

在 Startup 中,您需要在管道的开头添加中间件

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
{ 
    loggerFactory.AddConsole(Configuration.GetSection("Logging")); 
    loggerFactory.AddDebug(); 

    app.UseMiddleware<RequestLoggingMiddleware>();

    // rest of the middlewares 
      ..................

    app.UseMvc(); 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM