如何将连接字符串传递给 Application Insights?

我有一个 .NET Core 3.1 控制台应用程序,并希望使用 appsettings.json 中指定的连接字符串对其进行配置。

这是测试应用程序的代码:

static void Main(string[] args)
{
    var configurationBuilder = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json")
        .AddEnvironmentVariables();

    // To be able to read configuration from .json files
    var configuration = configurationBuilder.Build();

    // Create the DI container.
    IServiceCollection services = new ServiceCollection();

    services.AddApplicationInsightsTelemetryWorkerService();

    // Build ServiceProvider.
    IServiceProvider serviceProvider = services.BuildServiceProvider();

    // Obtain TelemetryClient instance from DI, for additional manual tracking or to flush.
    var telemetryClient = serviceProvider.GetRequiredService<TelemetryClient>();

    telemetryClient.TrackTrace("Hello, world 3!");

    // Explicitly call Flush() followed by sleep is required in Console Apps.
    // This is to ensure that even if application terminates, telemetry is sent to the back-end.
    telemetryClient.Flush();
    Task.Delay(5000).Wait();
}

问题是 Application Insight 似乎没有拾取连接字符串。我在 Application Insights 中看不到任何跟踪消息。如果我将检测密钥传递给 AddApplicationInsightsTelemetryWorkerService 它可以工作。

这是 appsettings.json 的内容:

{
  "ApplicationInsights": {
    "ConnectionString": "<my connection string>"
  }
}

我错过了什么?

stack overflow How to pass connection string to Application Insights?
原文答案

答案:

作者头像

我不知道问题是否仍然存在,但您可以将连接字符串直接传递给 TelemetryConfiguration。

var telemetryConfiguration = TelemetryConfiguration.CreateDefault();
telemetryConfiguration.ConnectionString = Configuration["AzureApplicationInsightsConnectionString"];

或者,您可以将其添加到 servicecollection:

var options = new ApplicationInsightsServiceOptions { ConnectionString = Configuration["AzureApplicationInsightsConnectionString"] };
services.AddApplicationInsightsTelemetry(options: options);