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

时间:2021-01-03 08:56:30

标签: 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 时,我看到信息日志尚未注册。我想知道我的错误。提前致谢。

4 个答案:

答案 0 :(得分:2)

看起来像 LogLevel 的问题:

配置说明:错误

"ApplicationInsights": {
    "LogLevel": {
      "Default": "Error"
    }
  }

但是在记录时,您正在 LogLevel:LogInformation

私有异步任务日志请求(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;

}

Tyring 将 LogLevel 更改为“错误”。

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

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

答案 1 :(得分:1)

您是否将 NLogger Application Insights 包包含到您的项目中?

尝试将其添加到您的项目中: https://www.nuget.org/packages/Microsoft.Extensions.Logging.ApplicationInsights/ (see this for ref.)

您还可以更改 ApplicationInsights 设置中的 LogLevel,因为现在在您的应用程序中,当您登录 Error 级别时,它似乎只收集 Information 级别。您可以尝试将其更改为 Debug,如下所示:

...
"ApplicationInsights": {
  "LogLevel": {
    "Default": "Debug"
  },
...

答案 2 :(得分:1)

您指定的配置对 <CollectionView x:Name="addOnList" Margin="0,40,0,0" Grid.Row="1" SelectionMode="Single" VerticalScrollBarVisibility="Never"> <CollectionView.ItemsLayout> <GridItemsLayout Orientation="Vertical" VerticalItemSpacing="20" HorizontalItemSpacing="20" Span="2"/> </CollectionView.ItemsLayout> <CollectionView.ItemTemplate> <DataTemplate> <Grid Padding="10" BackgroundColor="#131313" WidthRequest="145" HeightRequest="160"> <Grid.RowDefinitions> <RowDefinition Height="*"/> <RowDefinition Height="*"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <Image Aspect="Fill" Source="{Binding ThumbNail}" Margin="10" WidthRequest="200" HeightRequest="200" HorizontalOptions="Center" VerticalOptions="Center"/> <Label Grid.Row="1" Text="{Binding Name}" TextColor="#F9B522" FontFamily="ThemeFont" VerticalOptions="End" HorizontalOptions="Start"/> <Label Grid.Row="1" Text="{Binding Version}" TextColor="White" FontFamily="ThemeFont" VerticalOptions="End" HorizontalOptions="End"/> <Button Grid.Row="3" x:Name="btnSetReminder" Text="Add to Favourites"></Button> </Grid> </DataTemplate> </CollectionView.ItemTemplate> <CollectionView.Footer> <Grid HeightRequest="0"/> </CollectionView.Footer> </CollectionView> 应用日志过滤,提供程序别名为 ApplicationInsightsLoggerProvider。默认日志级别是信息,但对于提供程序 ApplicationInsights,它被覆盖为 ApplicationInsights 级别

Error

要解决此问题,您可以将 "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" }, "ApplicationInsights": { "LogLevel": { "Default": "Error" } } 默认的日志级别更改为 Informatio 并将 ApplicationInsights 移至 ApplicationInsights 部分。

Logging

阅读Control logging level

这里还有一点,您正在创建一个新的日志条目来记录请求的请求和响应详细信息/正文。因此,您不需要新的日志条目,您可以更新现有请求遥测中的详细信息。您可以参考 this repo 中提到的代码,该代码可以进一步扩展以记录其他详细信息,并且它还提供在记录请求正文期间删除敏感信息的功能(可以扩展为响应正文)。

答案 3 :(得分:1)

update table a set (a.codeid_a,a.col2,a.col3...) = (b.codeid_b,b.col2,b.col3...) from tableb b where b.claimsid_b = a.claimsid_a 文件中有 2 个错误:

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

  2. 然后将 "ApplicationInsights" 部分放入 Logging 部分。如下图:

    appsettings.json