如何从 .net core 6 记录应用程序洞察

l--*_*''' 1 c# azure-application-insights azure-functions .net-6.0

我有一个包含 2 个项目的解决方案:

  1. 函数应用程序项目
  2. web api .net core 6.0项目

函数应用程序成功记录到应用程序见解,但 Web api 项目却没有!Azure 门户显示这两个项目都配置为写入应用程序见解的同一实例。

两个不同的资源写入同一个应用程序见解实例是否存在问题?如果不是,我做错了什么?

Ant*_* G. 5

要使用遥测配置 Application Insights,您需要独立配置遥测和日志记录。手动配置或基于配置的约定都可以使用:

https://learn.microsoft.com/en-us/azure/azure-monitor/app/asp-net-core?tabs=netcore6

配置 DI 时手动设置选项:

public void ConfigureServices(IServiceCollection service)
{
    // ...
    ApplicationInsightsServiceOptions telemetryOptions = new ();
telemetryOptions.InstrumentationKey = YourInstrumentationKey;

    // Can enable/disable adaptive sampling here.
    // https://learn.microsoft.com/en-us/azure/azure-monitor/app/sampling
    telemetryOptions.EnableAdaptiveSampling = false;
    services.AddApplicationInsightsTelemetry(telemetryOptions);

    services.AddLogging(logBuilder =>
             {
                 logBuilder.AddApplicationInsights(YourInstrumentationKey)
                     // adding custom filter for specific use case. 
                     .AddFilter("Orleans", (level) => level == LogLevel.Error);
    });
    // ...
} 
Run Code Online (Sandbox Code Playgroud)

使用时appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ApplicationInsights": {
    "ConnectionString": "Copy connection string from Application Insights Resource Overview"
  }
}
Run Code Online (Sandbox Code Playgroud)

那么 DI 可以稍微简化一下:

public void ConfigureServices(IServiceCollection service)
{
    // ...
    services.AddApplicationInsightsTelemetry();
    services.AddLogging(logBuilder => logBuilder.AddApplicationInsights()});
    // ...
} 
Run Code Online (Sandbox Code Playgroud)

  • 请注意,不建议直接使用 InstrumentationKey,这已经过时了。MSFT 建议使用 App Insight 连接字符串。 (2认同)