将Application Insights与ILoggerFactory一起使用

我正在尝试将exception记录到Application Insights。 我通过直接调用TelemetryClient.TrackException成功完成了这项工作。 但是,我想在我的代码中抽象出来,以防我将来想要登录其他平台,所以我想只关注ILogger接口。

我发现你可以使用ILoggerFactory.AddApplicationInsights ( 这里实现),但不管我做了什么,我都没有看到日志在ApplicationInsights中出现。

以下是我的代码:

Startup.cs

  IConfigurationRoot Configuration { get; set; } ILoggerFactory LoggerFactory { get; set; } IServiceProvider ServiceProvider { get; set; } public Startup( IHostingEnvironment hostingEnvironment, ILoggerFactory loggerFactory ) { this.LoggerFactory = loggerFactory; string configurationFilePath = "abc.json"; this.Configuration = new ConfigurationBuilder() .SetBasePath( hostingEnvironment.ContentRootPath ) .AddJsonFile( configurationFilePath, optional: true, reloadOnChange: true ) .AddEnvironmentVariables() .Build(); } public void Configure( IApplicationBuilder applicationBuilder, IHostingEnvironment hostingEnvironment, ILoggerFactory loggerFactory, IServiceProvider serviceProvider ) { this.ServiceProvider = serviceProvider; loggerFactory.AddApplicationInsights( serviceProvider ); applicationBuilder.UseMvc(); } public void ConfigureServices( IServiceCollection services ) { services.AddApplicationInsightsTelemetry( this.Configuration ); services.AddMvc( .... // A bunch of options here ... ) } 

然后,我尝试在我的控制器中使用这个:

  ILogger Logger { get; set; } public XController( ILogger logger ) { this.Logger = logger; } [HttpPost] [Route( "v3.0/abcd" )] public async Task PostEvent( [FromBody] XEvent xEvent ) { this.Logger.LogError( 0, new Exception( "1234" ), "1234" ); } 

但是,我根本没有看到与请求相关的任何exception。 如果我用TelemetryClient.TrackException替换Logger.LogError行(并首先创建TelemetryClient ),那么我可以看到exception没有任何问题。

我不知道我做错了什么。 有人可以帮忙吗?

根据您的描述,我建议您可以尝试以下代码以启用ILogger将错误记录到ApplicationInsights。

您可以直接使用loggerFactory.AddApplicationInsights()方法来启用ApplicationInsights ILogger。

更多细节,您可以参考以下代码:

启动类:

 public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddApplicationInsightsTelemetry(Configuration); // Add framework services. services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddApplicationInsights(app.ApplicationServices,LogLevel.Warning); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } 

appsettings.json:

 { "ApplicationInsights": { "InstrumentationKey": "yourkey" } } 

结果:

在此处输入图像描述

在此处输入图像描述


更新:

记录在搜索function中找到。

在此处输入图像描述

我终于想通了。 有两种方法可以解决我的问题:

简单的方法:

我使用的是旧版本的Application Insights NuGets。 具体来说, Microsoft.ApplicationInsights.2.2.0Microsoft.ApplicationInsights.AspNetCore.2.0.0

一旦我升级到Microsoft.ApplicationInsights.2.4.0Microsoft.ApplicationInsights.AspNetCore.2.1.1 ,一切都按预期工作。 您还会看到LogXXX的exception作为显示为Exception的参数,并且没有exception显示为预期的Trace。

稍微困难的方式:

出于某种原因, Configure中的IApplicationBuilderIServiceProvider不提供在AddApplicationInsights使用的正确服务提供程序,因此您需要在ConfigureServices中添加提供程序:

  public void ConfigureServices( IServiceCollection services ) { IServiceProvider serviceProvider = services.BuildServiceProvider(); this.LoggerFactory.AddApplicationInsights( serviceProvider, Extensions.Logging.LogLevel.Information ); ... } 

这意味着您需要将loggerFactory从构造函数保存到属性/字段中,因为它不能通过ConfigureServicesdependency injection来使用。

我最终做了什么(在我看来可能是目前最好的解决方案):

即使只是做上述任何一种解决方案都能解决问题,我决定同时做到这两点。 这是因为我希望能够在ConfigureServices记录错误。 如果我将loggerFactory.UseApplicationInsights放在Configure ,那么我将无法在ApplicationInsights上的ConfigureServices看到错误。 我也更喜欢看Traces和Exceptions,这个function只附带新的软件包版本。

不幸的是,SDK最近才更新为触发Exception Telemetry(请参阅commit ),并且尚未发布更改。
我现在看到的唯一路由是在代码中保留对TelemetryClient.TrackException的显式调用,或者用你自己的ILogger实现将它们全部包装起来 – 两者都作为临时解决方案,直到官方SDK支持这个