c# - Web API 未在 Application Insights 和 ASP .Net Core 中注册信息日志

标签 c# azure asp.net-core azure-application-insights

我尝试使用 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

私有(private)异步任务LogRequest(HttpContext上下文) { 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 更改为“错误”。

并在启动类中检查以下配置设置:

public partial class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddApplicationInsightsTelemetry("InstrumentationKey");
    }
}

关于c# - Web API 未在 Application Insights 和 ASP .Net Core 中注册信息日志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65548104/

相关文章:

c# - 无法识别的属性disableAlternativeTemplates

c# - 有人可以告诉我 List、Collection 和 Enumerable 之间有什么区别?

entity-framework - 构建/构建 Azure 移动应用服务 Entity Framework 代码优先和 .NET APK 项目

AzureAppConfiguration.KeyVaultReferenceException : ClientSecretCredential authentication failed: A configuration issue is preventing authentication

asp.net-mvc - 遥测初始化程序失败 : Could not load "Microsoft.AspNet.TelemetryCorrelation"

c# - 使用 Entity Framework 6 流式传输 varbinary(max) 数据

c# - 进程是否在远程机器上运行?

c# - 安装 net core 后加载 hostfxr.dll 失败

asp.net-mvc - ASP.NET MVC 删除方法将 Id/model 传递给 Controller

c# - 如何从asp.net core mvc html helper静态方法中的html helper上下文获取urlHelper