用于 Microsoft.Extension.Logging 的 ApplicationInsightsLoggerProviderApplicationInsightsLoggerProvider for Microsoft.Extension.Logging

本文演示如何使用 ApplicationInsightsLoggerProvider 捕获控制台和 ASP.NET Core 应用程序中的 ILogger 日志。This article demonstrates how to use ApplicationInsightsLoggerProvider to capture ILogger logs in console and ASP.NET Core applications. 若要详细了解日志记录,请参阅 ASP.NET Core 中的日志记录To learn more logging, see Logging in ASP.NET Core.

ASP.NET Core 应用程序ASP.NET Core applications

使用代码无代码方法配置 ApplicationInsights 时,默认为 ASP.NET Core 应用程序启用 ApplicationInsightsLoggerProviderApplicationInsightsLoggerProvider is enabled by default for ASP.NET Core applications when ApplicationInsights is configured using Code or Code-less approach.

默认情况下,仅将“警告”及以上级别的 ILogger 日志(来自所有类别)发送到 Application Insights。Only Warning and above ILogger logs (from all categories) are sent to Application Insights by default. 但可自定义此行为But you can customize this behavior. Program.csStartup.cs 捕获 ILogger 日志需要执行额外的步骤。Additional steps are required to capture ILogger logs from Program.cs or Startup.cs. (请参阅在 ASP.NET Core 应用程序中从 Startup.cs 和 Program.cs 捕获 ILogger 日志。)(See Capturing ILogger logs from Startup.cs and Program.cs in ASP.NET Core applications.)

如果只想使用 ApplicationInsightsLoggerProvider,而不启用任何其他 Application Insights 监视,请使用以下步骤。If you want to just use ApplicationInsightsLoggerProvider without any other Application Insights monitoring, use the following steps.

  1. 安装 NuGet 包:Install the NuGet package:

     <ItemGroup>
         <PackageReference Include="Microsoft.Extensions.Logging.ApplicationInsights" Version="2.15.0" />  
     </ItemGroup>
    
  2. 按如下所示修改 Program.csModify Program.cs as shown here:

    using Microsoft.AspNetCore;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Logging;
    
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }
    
        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
          WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
          .ConfigureLogging(
                builder =>
                {
                    // Providing an instrumentation key here is required if you're using
                    // standalone package Microsoft.Extensions.Logging.ApplicationInsights
                    // or if you want to capture logs from early in the application startup
                    // pipeline from Startup.cs or Program.cs itself.
                    builder.AddApplicationInsights("put-actual-ikey-here");
    
                    // Optional: Apply filters to control what logs are sent to Application Insights.
                    // The following configures LogLevel Information or above to be sent to
                    // Application Insights for all categories.
                    builder.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>
                                     ("", LogLevel.Information);
                }
            );
    }
    

步骤 2 中的代码将配置 ApplicationInsightsLoggerProviderThe code in step 2 configures ApplicationInsightsLoggerProvider. 以下代码演示了一个使用 ILogger 发送日志的示例 Controller 类。The following code shows an example Controller class, which uses ILogger to send logs. Application Insights 将捕获日志。The logs are captured by Application Insights.

public class ValuesController : ControllerBase
{
    private readonly ILogger _logger;

    public ValuesController(ILogger<ValuesController> logger)
    {
        _logger = logger;
    }

    // GET api/values
    [HttpGet]
    public ActionResult<IEnumerable<string>> Get()
    {
        _logger.LogWarning("An example of a Warning trace..");
        _logger.LogError("An example of an Error level message");
        return new string[] { "value1", "value2" };
    }
}

在 ASP.NET Core 应用中从 Startup.cs 和 Program.cs 捕获 ILogger 日志Capture ILogger logs from Startup.cs and Program.cs in ASP.NET Core apps

备注

在 ASP.NET Core 3.0 及更高版本中,无法再在 Startup.cs 和 Program.cs 中注入 ILoggerIn ASP.NET Core 3.0 and later, it is no longer possible to inject ILogger in Startup.cs and Program.cs. 有关详细信息,请参阅 https://github.com/aspnet/Announcements/issues/353See https://github.com/aspnet/Announcements/issues/353 for more details.

ApplicationInsightsLoggerProvider 可以在应用程序启动初期捕获日志。ApplicationInsightsLoggerProvider can capture logs from early in the application startup. 虽然 ApplicationInsightsLoggerProvider 在 Application Insights(从 2.7.1 版开始)中已自动启用,但它直到稍后进入管道才设置检测密钥。Although ApplicationInsightsLoggerProvider is automatically enabled in Application Insights (starting with version 2.7.1), it doesn't have an instrumentation key set up until later in the pipeline. 因此,只会从 Controller/其他类捕获日志。So, only logs from Controller/other classes will be captured. 若要捕获从 Program.csStartup.cs 本身开始的每个日志,必须显式为 ApplicationInsightsLoggerProvider 启用检测密钥。To capture every log starting with Program.cs and Startup.cs itself, you must explicitly enable an instrumentation key for ApplicationInsightsLoggerProvider. 此外,在从 Program.csStartup.cs 本身记录日志时,不会完全设置 TelemetryConfigurationAlso, TelemetryConfiguration is not fully set up when you log from Program.cs or Startup.cs itself. 因此,这些日志将采用最低的配置,该配置使用 InMemoryChannel,不使用采样,且不使用标准的遥测初始化表达式或处理器So those logs will have a minimum configuration that uses InMemoryChannel, no sampling, and no standard telemetry initializers or processors.

以下示例使用 Program.csStartup.cs 演示此功能。The following examples demonstrate this capability with Program.cs and Startup.cs.

示例 Program.csExample Program.cs

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Logging;

public class Program
{
    public static void Main(string[] args)
    {
        var host = CreateWebHostBuilder(args).Build();
        var logger = host.Services.GetRequiredService<ILogger<Program>>();
        logger.LogInformation("From Program. Running the host now..");
        host.Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .ConfigureLogging(
        builder =>
            {
            // Providing an instrumentation key here is required if you're using
            // standalone package Microsoft.Extensions.Logging.ApplicationInsights
            // or if you want to capture logs from early in the application startup 
            // pipeline from Startup.cs or Program.cs itself.
            builder.AddApplicationInsights("ikey");

            // Adding the filter below to ensure logs of all severity from Program.cs
            // is sent to ApplicationInsights.
            builder.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>
                             (typeof(Program).FullName, LogLevel.Trace);

            // Adding the filter below to ensure logs of all severity from Startup.cs
            // is sent to ApplicationInsights.
            builder.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>
                             (typeof(Startup).FullName, LogLevel.Trace);
            }
        );
}

示例 Startup.csExample Startup.cs

public class Startup
{
    private readonly ILogger _logger;

    public Startup(IConfiguration configuration, ILogger<Startup> logger)
    {
        Configuration = configuration;
        _logger = logger;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddApplicationInsightsTelemetry();

        // The following will be picked up by Application Insights.
        _logger.LogInformation("Logging from ConfigureServices.");
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            _logger.LogInformation("Configuring for Development environment");
            app.UseDeveloperExceptionPage();
        }
        else
        {
            _logger.LogInformation("Configuring for Production environment");
        }

        app.UseMvc();
    }
}

从旧的 ApplicationInsightsLoggerProvider 迁移Migrate from the old ApplicationInsightsLoggerProvider

2.7.1 之前的 Microsoft.ApplicationInsights.AspNet SDK 版本支持的某个日志记录提供程序现已过时。Microsoft.ApplicationInsights.AspNet SDK versions before 2.7.1 supported a logging provider that's now obsolete. 此提供程序是通过 ILoggerFactory 的 AddApplicationInsights() 扩展方法启用的。This provider was enabled through the AddApplicationInsights() extension method of ILoggerFactory. 我们建议迁移到新的提供程序,这涉及到两个步骤:We recommend that you migrate to the new provider, which involves two steps:

  1. Startup.Configure() 方法中删除 ILoggerFactory.AddApplicationInsights() 调用,以避免重复日志记录。Remove the ILoggerFactory.AddApplicationInsights() call from the Startup.Configure() method to avoid double logging.
  2. 在代码中重新应用任何筛选规则,因为新提供程序不遵循旧规则。Reapply any filtering rules in code, because they will not be respected by the new provider. ILoggerFactory.AddApplicationInsights() 的重载采用最低的 LogLevel 或筛选函数。Overloads of ILoggerFactory.AddApplicationInsights() took minimum LogLevel or filter functions. 在新提供程序中,筛选是日志记录框架本身的一部分。With the new provider, filtering is part of the logging framework itself. Application Insights 提供程序不会执行筛选。It's not done by the Application Insights provider. 因此,应删除通过 ILoggerFactory.AddApplicationInsights() 重载提供的所有筛选器。So any filters that are provided via ILoggerFactory.AddApplicationInsights() overloads should be removed. 应该遵照控制日志记录级别中的说明提供筛选规则。And filtering rules should be provided by following the Control logging level instructions. 如果使用 appsettings.json 筛选日志记录,此筛选可继续在新提供程序中进行,因为两者使用相同的提供程序别名 ApplicationInsightsIf you use appsettings.json to filter logging, it will continue to work with the new provider, because both use the same provider alias, ApplicationInsights.

仍可以使用旧的提供程序。You can still use the old provider. (旧提供程序只会在 3.xx 主要版本中删除。)但是,我们建议迁移到新提供程序,原因如下:(It will be removed only in a major version change to 3.xx.) But we recommend that you migrate to the new provider for the following reasons:

  • 以前的提供程序缺少对日志范围的支持。The previous provider lacks support for log scopes. 在新提供程序中,范围中的属性将作为自定义属性自动添加到收集的遥测数据。In the new provider, properties from scope are automatically added as custom properties to the collected telemetry.
  • 现在,可以在应用程序启动管道中更早地捕获日志。Logs can now be captured much earlier in the application startup pipeline. 现在可以从 ProgramStartup 类捕获日志。Logs from the Program and Startup classes can now be captured.
  • 在新提供程序中,筛选是在框架级别本身上执行的。With the new provider, filtering is done at the framework level itself. 在 Application Insights 提供程序中,可以像在其他提供程序(包括 Console、Debug 等内置提供程序)中一样筛选日志。You can filter logs to the Application Insights provider in the same way as for other providers, including built-in providers like Console, Debug, and so on. 还可以将相同的筛选器应用到多个提供程序。You can also apply the same filters to multiple providers.
  • 在 ASP.NET Core(2.0 和更高版本)中,启用日志记录提供程序的建议方式是在 Program.cs 本身中的 ILoggingBuilder 上使用扩展方法。In ASP.NET Core (2.0 and later), the recommended way to enable logging providers is by using extension methods on ILoggingBuilder in Program.cs itself.

备注

新提供程序适用于面向 NETSTANDARD2.0 或更高版本的应用程序。The new provider is available for applications that target NETSTANDARD2.0 or later. Microsoft.ApplicationInsights.AspNet SDK 版本 2.14.0 起,新的提供程序也可用于面向 .NET Framework NET461 或更高版本的应用程序。From Microsoft.ApplicationInsights.AspNet SDK version 2.14.0 onwards, new provider is also available for applications that target .NET Framework NET461 or later. 如果应用程序面向较低的 .NET Core 版本(例如 .NET Core 1.1)或者面向低于 NET46 的 .NET Framework,请继续使用旧提供程序。If your application targets older .NET Core versions, such as .NET Core 1.1, or if it targets the .NET Framework less than NET46, continue to use the old provider.

控制台应用程序Console application

备注

有一个名为 Microsoft.ApplicationInsights.WorkerService 的新 Application Insights SDK,可用于为任何控制台应用程序启用 Application Insights(ILogger 和其他 Application Insights 遥测)。There is a new Application Insights SDK called Microsoft.ApplicationInsights.WorkerService which can used to enable Application Insights (ILogger and other Application Insights telemetry) for any Console Applications. 建议在此处使用此包和相关说明。It is recommended to use this package and associated instructions from here.

如果只想使用 ApplicationInsightsLoggerProvider,而不启用任何其他 Application Insights 监视,请使用以下步骤。If you want to just use ApplicationInsightsLoggerProvider without any other Application Insights monitoring, use the following steps.

已安装的包:Packages installed:

<ItemGroup>
  <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="2.1.0" />  
  <PackageReference Include="Microsoft.Extensions.Logging.ApplicationInsights" Version="2.15.0" />  
</ItemGroup>
class Program
{
    static void Main(string[] args)
    {
        // Create the DI container.
        IServiceCollection services = new ServiceCollection();

        // Channel is explicitly configured to do flush on it later.
        var channel = new InMemoryChannel();
        services.Configure<TelemetryConfiguration>(
            (config) =>
            {
                config.TelemetryChannel = channel;
            }
        );

        // Add the logging pipelines to use. We are using Application Insights only here.
        services.AddLogging(builder =>
        {
            // Optional: Apply filters to configure LogLevel Trace or above is sent to
            // Application Insights for all categories.
            builder.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>
                             ("", LogLevel.Trace);
            builder.AddApplicationInsights("--YourAIKeyHere--");
        });

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

        ILogger<Program> logger = serviceProvider.GetRequiredService<ILogger<Program>>();

        logger.LogInformation("Logger is working");

        // 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.
        channel.Flush();
        Thread.Sleep(1000);
    }
}

此示例使用独立包 Microsoft.Extensions.Logging.ApplicationInsightsThis example uses the standalone package Microsoft.Extensions.Logging.ApplicationInsights. 默认情况下,此配置使用最低的 TelemetryConfiguration 将数据发送到 Application Insights。By default, this configuration uses the "bare minimum" TelemetryConfiguration for sending data to Application Insights. “最低”表示 InMemoryChannel 是使用的通道。Bare minimum means that InMemoryChannel is the channel that's used. 它不使用采样,也不使用标准的 TelemetryInitializer。There's no sampling and no standard TelemetryInitializers. 可为控制台应用程序重写此行为,如以下示例所示。This behavior can be overridden for a console application, as the following example shows.

安装此附加包:Install this additional package:

<PackageReference Include="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel" Version="2.9.1" />

以下部分介绍如何使用 services.Configure<TelemetryConfiguration>() 方法重写默认的 TelemetryConfiguration。The following section shows how to override the default TelemetryConfiguration by using the services.Configure<TelemetryConfiguration>() method. 此示例设置 ServerTelemetryChannel 和采样。This example sets up ServerTelemetryChannel and sampling. 它将自定义的 ITelemetryInitializer 添加到 TelemetryConfiguration。It adds a custom ITelemetryInitializer to the TelemetryConfiguration.

    // Create the DI container.
    IServiceCollection services = new ServiceCollection();
    var serverChannel = new ServerTelemetryChannel();
    services.Configure<TelemetryConfiguration>(
        (config) =>
        {
            config.TelemetryChannel = serverChannel;
            config.TelemetryInitializers.Add(new MyTelemetryInitalizer());
            config.DefaultTelemetrySink.TelemetryProcessorChainBuilder.UseSampling(5);
            serverChannel.Initialize(config);
        }
    );
    
    services.AddLogging(loggingBuilder =>
    {
        loggingBuilder.AddApplicationInsights("--YourAIKeyHere--");
    });

    ........
    ........

    // Explicitly calling Flush() followed by sleep is required in Console Apps.
    // This is to ensure that even if the application terminates, telemetry is sent to the back end.
    serverChannel.Flush();
    Thread.Sleep(1000);

控制日志记录级别Control logging level

ILogger 具有内置机制,可应用日志筛选ILogger has a built-in mechanism to apply log filtering. 这样,就可以控制发送到每个已注册的提供程序(包括 Application Insights 提供程序)的日志。This lets you control the logs that are sent to each registered provider, including the Application Insights provider. 可以在配置中(通常是使用 appsettings.json 文件)或者在代码中执行筛选。The filtering can be done either in configuration (typically by using an appsettings.json file) or in code.

以下示例说明如何对 ApplicationInsightsLoggerProvider 应用筛选规则。The following examples show how to apply filter rules to ApplicationInsightsLoggerProvider.

使用 appsettings.json 在配置中创建筛选规则Create filter rules in configuration with appsettings.json

对于 ApplicationInsightsLoggerProvider,提供程序别名为 ApplicationInsightsFor ApplicationInsightsLoggerProvider, the provider alias is ApplicationInsights. appsettings.json 的以下节指示日志记录提供程序在“警告”级别及更高级别进行记录(通常情况下)。The following section of appsettings.json instructs logging providers generally to log at level Warning and above. 然后,它重写 ApplicationInsightsLoggerProvider 以记录在“错误”及更高级别以“Microsoft”开头的类别。It then overrides the ApplicationInsightsLoggerProvider to log categories that start with "Microsoft" at level Error and above.

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    },
    "ApplicationInsights": {
      "LogLevel": {
        "Microsoft": "Error"
      }
    }
  }
}

在代码中创建筛选规则Create filter rules in code

以下代码片段配置所有类别中“警告”和更高级别的日志,以及以“Microsoft”开头的类别中要发送到 ApplicationInsightsLoggerProvider 的“错误”和更高级别的日志。 The following code snippet configures logs for Warning and above from all categories and for Error and above from categories that start with "Microsoft" to be sent to ApplicationInsightsLoggerProvider. 此配置是与前面的 appsettings.json 节中的配置相同。This configuration is the same as in the previous section in appsettings.json.

    WebHost.CreateDefaultBuilder(args)
    .UseStartup<Startup>()
    .ConfigureLogging(logging =>
      logging.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>
                        ("", LogLevel.Warning)
             .AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>
                        ("Microsoft", LogLevel.Error);

日志记录范围Logging Scopes

ApplicationInsightsLoggingProvider 支持日志范围,且默认启用范围。ApplicationInsightsLoggingProvider supports Log Scopes and scopes are enabled by default.

如果范围的类型为 IReadOnlyCollection<KeyValuePair<string,object>>,则集合中的每个键值对都将作为自定义属性添加到 Application Insights 遥测中。If the scope is of type IReadOnlyCollection<KeyValuePair<string,object>>, then each key-value pair in the collection is added to the application insights telemetry as custom properties. 在下面的示例中,日志将作为 TraceTelemetry 捕获,其属性中将包含(“MyKey”和“MyValue”)。In the example below, logs will be captured as TraceTelemetry and will have ("MyKey", "MyValue") in properties.

    using (_logger.BeginScope(new Dictionary<string, object> { { "MyKey", "MyValue" } }))
    {
        _logger.LogError("An example of an Error level message");
    }

如果将任何其他类型用作范围,则它们将存储在 Application Insights 遥测中的属性“Scope”下。If any other type is used as Scope, then they will be stored under the property "Scope" in application insights telemetry. 在下面的示例中,TraceTelemetry 将具有名为“Scope”的属性,其中包含范围。In the example below, the TraceTelemetry will have a property called "Scope" containing the scope.

    using (_logger.BeginScope("hello scope"))
    {
        _logger.LogError("An example of an Error level message");
    }

常见问题Frequently asked questions

ApplicationInsightsLoggerProvider 的旧版本和新版本是什么?What are the old and new versions of ApplicationInsightsLoggerProvider?

Microsoft.ApplicationInsights.AspNet SDK 包含已通过 ILoggerFactory 扩展方法启用的内置 ApplicationInsightsLoggerProvider (Microsoft.ApplicationInsights.AspNetCore.Logging.ApplicationInsightsLoggerProvider)。Microsoft.ApplicationInsights.AspNet SDK included a built-in ApplicationInsightsLoggerProvider (Microsoft.ApplicationInsights.AspNetCore.Logging.ApplicationInsightsLoggerProvider), which was enabled through ILoggerFactory extension methods. 从版本 2.7.1 开始,此提供程序已标记为过时。This provider is marked obsolete from version 2.7.1. 在下一次主要版本更改中,会彻底删除此提供程序。It will be removed completely in the next major version change. Microsoft.ApplicationInsights.AspNetCore 2.6.1 包本身尚未过时。The Microsoft.ApplicationInsights.AspNetCore 2.6.1 package itself isn't obsolete. 对请求、依赖项等启用监视需要用到它。It's required to enable monitoring of requests, dependencies, and so on.

建议的替代方法是安装新的独立包 Microsoft.Extensions.Logging.ApplicationInsights,其中包含改进的 ApplicationInsightsLoggerProvider (Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider),以及 ILoggerBuilder 中用于启用该提供程序的扩展方法。The suggested alternative is the new standalone package Microsoft.Extensions.Logging.ApplicationInsights, which contains an improved ApplicationInsightsLoggerProvider (Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider) and extension methods on ILoggerBuilder for enabling it.

Microsoft.ApplicationInsights.AspNet SDK 版本 2.7.1 依赖于新包,可自动启用 ILogger 捕获。Microsoft.ApplicationInsights.AspNet SDK version 2.7.1 takes a dependency on the new package and enables ILogger capture automatically.

为何某些 ILogger 日志在 Application Insights 中会显示两次?Why are some ILogger logs shown twice in Application Insights?

如果通过对 ILoggerFactory 调用 AddApplicationInsights 来启用旧版(现在过时)ApplicationInsightsLoggerProvider,则可能会出现重复项。Duplication can occur if you have the older (now obsolete) version of ApplicationInsightsLoggerProvider enabled by calling AddApplicationInsights on ILoggerFactory. 检查 Configure 方法是否包含以下内容,如有则将其删除:Check if your Configure method has the following, and remove it:

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
 {
     loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Warning);
     // ..other code.
 }

如果在 Visual Studio 中调试时看到重复的日志,请在启用 Application Insights 的代码中将 EnableDebugLogger 设置为 false,如下所示。If you experience double logging when you debug from Visual Studio, set EnableDebugLogger to false in the code that enables Application Insights, as follows. 这种重复现象和修复方法仅与调试应用程序时的情况相关。This duplication and fix is only relevant when you're debugging the application.

 public void ConfigureServices(IServiceCollection services)
 {
     ApplicationInsightsServiceOptions options = new ApplicationInsightsServiceOptions();
     options.EnableDebugLogger = false;
     services.AddApplicationInsightsTelemetry(options);
     // ..other code.
 }

我已更新到 Microsoft.ApplicationInsights.AspNet SDK 版本 2.7.1,现在可以自动捕获 ILogger 中的日志。I updated to Microsoft.ApplicationInsights.AspNet SDK version 2.7.1, and logs from ILogger are captured automatically. 如何完全禁用此功能?How do I turn off this feature completely?

请参阅控制日志记录级别部分有关如何筛选日志的一般信息。See the Control logging level section to see how to filter logs in general. 若要禁用 ApplicationInsightsLoggerProvider,请使用 LogLevel.NoneTo turn-off ApplicationInsightsLoggerProvider, use LogLevel.None:

在代码中:In code:

    builder.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>
                      ("", LogLevel.None);

在配置中:In config:

{
  "Logging": {
    "ApplicationInsights": {
      "LogLevel": {
        "Default": "None"
      }
}

为何某些 ILogger 日志包含的属性与其他日志不同?Why do some ILogger logs not have the same properties as others?

Application Insights 使用对其他每项遥测功能所用的相同 TelemetryConfiguration 来捕获和发送 ILogger 日志。Application Insights captures and sends ILogger logs by using the same TelemetryConfiguration that's used for every other telemetry. 但存在一种例外情况。But there's an exception. 默认情况下,在从 Program.csStartup.cs 记录日志时,不会完全设置 TelemetryConfiguration。By default, TelemetryConfiguration is not fully set up when you log from Program.cs or Startup.cs. 来自这些位置的日志不采用默认配置,因此它们不会运行所有的 TelemetryInitializer 和 TelemetryProcessor。Logs from these places won't have the default configuration, so they won't be running all TelemetryInitializers and TelemetryProcessors.

我正在使用独立包 Microsoft.Extensions.Logging.ApplicationInsights,并想要手动记录一些附加的自定义遥测数据。I'm using the standalone package Microsoft.Extensions.Logging.ApplicationInsights, and I want to log some additional custom telemetry manually. 如何做到这一点?How should I do that?

使用独立包时,TelemetryClient 不会注入到 DI 容器,因此你需要创建 TelemetryClient 的新实例,并使用记录器提供程序所用的相同配置,如以下代码所示。When you use the standalone package, TelemetryClient is not injected to the DI container, so you need to create a new instance of TelemetryClient and use the same configuration as the logger provider uses, as the following code shows. 这可以确保对所有自定义遥测数据以及来自 ILogger 的遥测数据使用相同的配置。This ensures that the same configuration is used for all custom telemetry as well as telemetry from ILogger.

public class MyController : ApiController
{
   // This telemetryclient can be used to track additional telemetry using TrackXXX() api.
   private readonly TelemetryClient _telemetryClient;
   private readonly ILogger _logger;

   public MyController(IOptions<TelemetryConfiguration> options, ILogger<MyController> logger)
   {
        _telemetryClient = new TelemetryClient(options.Value);
        _logger = logger;
   }  
}

备注

如果使用 Microsoft.ApplicationInsights.AspNetCore 包启用 Application Insights,请修改此代码,以便在构造函数中直接获取 TelemetryClientIf you use the Microsoft.ApplicationInsights.AspNetCore package to enable Application Insights, modify this code to get TelemetryClient directly in the constructor. 有关示例,请参阅此常见问题解答For an example, see this FAQ.

将从 ILogger 日志生成哪种类型的 Application Insights 遥测数据?What Application Insights telemetry type is produced from ILogger logs? 或者,可以在何处查看 Application Insights 中的 ILogger 日志?Or where can I see ILogger logs in Application Insights?

ApplicationInsightsLoggerProvider 捕获 ILogger 日志,并基于这些日志创建 TraceTelemetry。ApplicationInsightsLoggerProvider captures ILogger logs and creates TraceTelemetry from them. 如果将 Exception 对象传递给 ILogger 上的 Log 方法,则会创建 ExceptionTelemetry,而不创建 TraceTelemetry。If an Exception object is passed to the Log method on ILogger, ExceptionTelemetry is created instead of TraceTelemetry. 在显示 Application Insights 的任何其他 TraceTelemetry 或 ExceptionTelemetry 的位置(包括门户、Analytics 或 Visual Studio 本地调试器),都可以找到这些遥测项。These telemetry items can be found in same places as any other TraceTelemetry or ExceptionTelemetry for Application Insights, including portal, analytics, or Visual Studio local debugger.

若要始终发送 TraceTelemetry,请使用此代码片段:builder.AddApplicationInsights((opt) => opt.TrackExceptionsAsExceptionTelemetry = false);If you prefer to always send TraceTelemetry, use this snippet: builder.AddApplicationInsights((opt) => opt.TrackExceptionsAsExceptionTelemetry = false);

我没有安装 SDK,而是使用 Azure Web 应用扩展来为 ASP.NET Core 应用程序启用 Application Insights。I don't have the SDK installed, and I use the Azure Web Apps extension to enable Application Insights for my ASP.NET Core applications. 如何使用新的提供程序?How do I use the new provider?

Azure Web 应用中的 Application Insights 扩展使用新提供程序。The Application Insights extension in Azure Web Apps uses the new provider. 可以在应用程序的 appsettings.json 文件中修改筛选规则。You can modify the filtering rules in the appsettings.json file for your application.

我正在使用独立包 Microsoft.Extensions.Logging.ApplicationInsights 并通过调用 builder.AddApplicationInsights("ikey") 来启用 Application Insights 提供程序。I'm using the standalone package Microsoft.Extensions.Logging.ApplicationInsights and enabling Application Insights provider by calling builder.AddApplicationInsights("ikey"). 是否有某个选项可从配置中获取检测密钥?Is there an option to get an instrumentation key from configuration?

请按如下所示修改 Program.cs 和 appsettings.json:Modify Program.cs and appsettings.json as follows:

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .ConfigureLogging((hostingContext, logging) =>
            {
                // hostingContext.HostingEnvironment can be used to determine environments as well.
                var appInsightKey = hostingContext.Configuration["myikeyfromconfig"];
                logging.AddApplicationInsights(appInsightKey);
            });
}

appsettings.json 中的相关节:Relevant section from appsettings.json:

{
  "myikeyfromconfig": "putrealikeyhere"
}

仅当使用独立的日志记录提供程序时,才需要提供此代码。This code is required only when you use a standalone logging provider. 对于常规的 Application Insights 监视,系统会自动从配置路径 ApplicationInsights:Instrumentationkey 中加载检测密钥。For regular Application Insights monitoring, the instrumentation key is loaded automatically from the configuration path ApplicationInsights: Instrumentationkey. Appsettings.json 应如下所示:Appsettings.json should look like this:

{
  "ApplicationInsights":
    {
        "Instrumentationkey":"putrealikeyhere"
    }
}

后续步骤Next steps

了解有关以下方面的详细信息:Learn more about: