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

奥马尔·穆尔西亚(Omar Murcia)

我正在尝试使用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时,我看到该信息日志尚未注册。我想知道我的错误。提前致谢。

杨van |

appsettings.json文件中有2个错误

  1. “ ApplicationInsights”部分中,将“默认”:“错误”更改为“默认”:“信息”

  2. 然后将“ ApplicationInsights”部分放入“日志记录”部分。如下所示:

       {
          "Logging": {
             "LogLevel": {
               "Default": "Information",
               "Microsoft": "Information",
               "Microsoft.Hosting.Lifetime": "Information"
             },
             "ApplicationInsights": {
               "LogLevel": {
                 "Default": "Information"
               }
             }
           },
    
         //other settings.
       }
    

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在ASP.NET Core Web API中注册新的DelegatingHandler

使用ASP.Net MVC和Web Api的Application Insights实时指标

限制访问权限以在ASP.NET Web API和身份中注册用户

ASP.NET Web API 2.0管道和ASP.NET Core Web API管道的区别

简单的喷油器注册ASP.NET身份和Web API

ASP.NET Web API日志记录和跟踪

Application Insights仅跟踪失败的ASP.NET MVC Web API请求

为什么 ASP.NET Web API 2 和 ASP.NET Core 3.1 Web API 之间的行为不同?

在ASP .NET Core Web API控制器中注入Serilog的ILogger接口

集成测试中的自定义WebApplicationFactory未在Startup.cs(ASP.NET Core 3.1)中注册服务

CORS和ASP.Net Web API

ASP.NET MVC和WEB API

调试asp.net core web API

使用Application Insights在Azure上进行ASP.NET Core跟踪日志记录

ASP.NET Core Application Insights 自适应采样

使用ASP.NET Core库禁用Application Insights采样

来自ASP.NET Core身份的Application Insights用户ID

ASP .Net Core Web 应用程序调用 Web API

如何从Web API调用ASP.NET Core Web MVC

如何从 .NET Core 2.1 中 Application Insights 的采样中排除异常和错误日志记录?

用于 ASP.NET Core 和 OData 的 REST Web API 中的 IQueryable、IEnumerable 和异步

ASP.NET Core Web API-JWT消息处理程序-没有注册的类型错误

使用 autofac 在 ASP.NET Core 3 中注册 IPipelineBehavior

在ASP.NET Core中注册子IOptions

Application Insights和.Net Core-0.0.0.0 IP

.Net Core Web API

具有外键关系的ASP.NET Core Web API和EF Core模型

返回“ application / xml”而不是“ text / plain” ASP.NET Core Web API

在Azure Service Fabric中,无状态Web API和ASP.NET Core Web API之间有什么区别?