![](/img/trans.png)
[英]How to log ASP.NET Web API request body into a Application Insights failure?
[英]Web API doesn't register Information log in Application Insights and ASP .Net Core
我正在尝试使用 ASP.Net Core 和 Application Insights 在中间件中记录请求和响应,但 Application Insights 不记录信息。 我的代码:
RequestResponseLoggingMiddleware.cs
public class RequestResponseLoggingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<RequestResponseLoggingMiddleware> _logger;
private readonly RecyclableMemoryStreamManager _recyclableMemoryStreamManager;
public RequestResponseLoggingMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
{
_next = next;
_logger = loggerFactory.CreateLogger<RequestResponseLoggingMiddleware>();
_recyclableMemoryStreamManager = new RecyclableMemoryStreamManager();
}
public async Task Invoke(HttpContext context)
{
await LogRequest(context);
await LogResponse(context);
}
private async Task LogRequest(HttpContext context)
{
context.Request.EnableBuffering();
await using var requestStream = _recyclableMemoryStreamManager.GetStream();
await context.Request.Body.CopyToAsync(requestStream);
_logger.LogInformation($"Http Request Information:{Environment.NewLine}" +
$"Schema:{context.Request.Scheme} " +
$"Host: {context.Request.Host} " +
$"Path: {context.Request.Path} " +
$"QueryString: {context.Request.QueryString} " +
$"Request Body: {ReadStreamInChunks(requestStream)}");
context.Request.Body.Position = 0;
}
private async Task LogResponse(HttpContext context)
{
var originalBodyStream = context.Response.Body;
await using var responseBody = _recyclableMemoryStreamManager.GetStream();
context.Response.Body = responseBody;
await _next(context);
context.Response.Body.Seek(0, SeekOrigin.Begin);
var text = await new StreamReader(context.Response.Body).ReadToEndAsync();
context.Response.Body.Seek(0, SeekOrigin.Begin);
_logger.LogInformation($"Http Response Information:{Environment.NewLine}" +
$"Schema:{context.Request.Scheme} " +
$"Host: {context.Request.Host} " +
$"Path: {context.Request.Path} " +
$"QueryString: {context.Request.QueryString} " +
$"Response Body: {text}");
await responseBody.CopyToAsync(originalBodyStream);
}
private static string ReadStreamInChunks(Stream stream)
{
const int readChunkBufferLength = 4096;
stream.Seek(0, SeekOrigin.Begin);
using var textWriter = new StringWriter();
using var reader = new StreamReader(stream);
var readChunk = new char[readChunkBufferLength];
int readChunkLength;
do
{
readChunkLength = reader.ReadBlock(readChunk, 0, readChunkBufferLength);
textWriter.Write(readChunk, 0, readChunkLength);
} while (readChunkLength > 0);
return textWriter.ToString();
}
}
appsettings.json
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"ApplicationInsights": {
"LogLevel": {
"Default": "Error"
},
"ConnectionString": "InstrumentationKey=deletedforskingthisquestion;IngestionEndpoint=https://centralus-0.in.applicationinsights.azure.com/"
},
当我检查我的 Application Insights 时,我看到该信息日志尚未注册。 我想知道我的错误。 提前致谢。
看起来像 LogLevel 的问题:
配置说:错误
"ApplicationInsights": {
"LogLevel": {
"Default": "Error"
}
}
但是在记录时,您正在查看 LogLevel: LogInformation
私有异步任务 LogRequest(HttpContext context) { context.Request.EnableBuffering();
await using var requestStream = _recyclableMemoryStreamManager.GetStream();
await context.Request.Body.CopyToAsync(requestStream);
_logger.LogInformation($"Http Request Information:{Environment.NewLine}" +
$"Schema:{context.Request.Scheme} " +
$"Host: {context.Request.Host} " +
$"Path: {context.Request.Path} " +
$"QueryString: {context.Request.QueryString} " +
$"Request Body: {ReadStreamInChunks(requestStream)}");
context.Request.Body.Position = 0;
}
试图将 LogLevel 更改为“错误”。
并在启动 class 中检查以下配置设置:
public partial class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddApplicationInsightsTelemetry("InstrumentationKey");
}
}
您是否将 NLogger Application Insights package 包含到您的项目中?
尝试将其添加到您的项目中: https://www.nuget.org/packages/Microsoft.Extensions.Logging.ApplicationInsights/ ( 请参阅this for ref。 )
您还可以更改ApplicationInsights
设置上的 LogLevel,因为现在在您的应用程序中登录Information
级别时,它似乎只收集Error
级别。 您可以尝试将其更改为 ie Debug
,如下所示:
...
"ApplicationInsights": {
"LogLevel": {
"Default": "Debug"
},
...
您指定的配置对ApplicationInsightsLoggerProvider
日志过滤,提供程序别名为ApplicationInsights
。 默认日志级别是信息,但对于提供ApplicationInsights
,它被覆盖为Error
级别
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
},
"ApplicationInsights": {
"LogLevel": {
"Default": "Error"
}
}
要解决此问题,您可以将ApplicationInsights
默认的日志级别更改为信息并将ApplicationInsights
移动到Logging
部分。
"ApplicationInsights": {
"LogLevel": {
"Default": "Information"
}
读取控制日志记录级别。
这里还有一点,您正在创建一个新的日志条目来记录请求的请求和响应详细信息/正文。 因此,您不需要新的日志条目,您可以更新现有请求遥测中的详细信息。 您可以参考此 repo中提到的代码,该代码可以进一步扩展以记录其他详细信息,并且它还提供了在记录请求正文期间删除敏感信息的能力(可以扩展为响应正文)。
appsettings.json
文件有2个错误:
在"ApplicationInsights"部分中,将"Default": "Error"更改为"Default": "Information" 。
然后将“ApplicationInsights”部分放入Logging部分。 如下所示:
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Information", "Microsoft.Hosting.Lifetime": "Information" }, "ApplicationInsights": { "LogLevel": { "Default": "Information" } } }, //other settings. }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.