我很難在ASP.NET Core Web API中捕獲用於日誌記錄的HTTP請求。我能在這裏找到一個例子ASP.Net核心Web API捕獲HTTP請求以進行日誌記錄
http://dotnetliberty.com/index.php/2016/01/07/logging-asp-net-5-requests-using-middleware/
這有助於。它基本上是一個使用中間件功能添加到HTTP請求管道中的日誌記錄類。問題是僅在應用程序啓動時才調用類方法。我無法在任何獲取或發佈的http請求中調用它。得到或發佈的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.Configure方法在我Startup.cs類
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>();
}
最後一行是我用捎帶到HTTP請求app.UseMiddleware。我認爲這應該起作用,但如果任何人有線索爲什麼它不會或替代品會很好。請讓我知道你是否應該提供更多信息。
此博客的開頭加上中間件涵蓋了你需要的東西:https://blog.getseq.net/smart-logging-middleware - 用於-ASP淨芯/ – IbrarMumtaz