将Application Insights与ILoggerFactory一起使用

时间:2017-07-10 22:36:53

标签: c# logging asp.net-core azure-web-app-service azure-application-insights

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

我发现您可以使用ILoggerFactory.AddApplicationInsights(已实施here),但无论我做了什么,我都没有看到日志显示在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<XController> Logger { get; set; }

    public XController( ILogger<XController> logger )
    {
        this.Logger = logger;
    }

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

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

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

5 个答案:

答案 0 :(得分:11)

根据您的描述,我建议您可以尝试使用以下代码启用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"
  }
}

结果:

enter image description here

enter image description here

更新

记录在搜索功能中找到。

enter image description here

答案 1 :(得分:3)

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

简单方法:

我使用的是旧版本的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的参数,并且没有异常显示为预期的跟踪。

稍微困难一点:

出于某种原因,IApplicationBuilder中的IServiceProviderConfigure无法在AddApplicationInsights中提供正确的服务提供商,因此您需要在ConfigureServices:

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

这意味着您需要将loggerFactory从构造函数保存到属性/字段中,因为它不能通过ConfigureServices中的依赖项注入来使用。

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

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

答案 2 :(得分:2)

不幸的是,SDK最近才更新为触发Exception Telemetry(请参阅commit),此更改尚未发布。
我现在看到的唯一路线是在代码中保留对TelemetryClient.TrackException的显式调用,或者使用您自己的ILogger实现将其全部包装 - 两者都作为临时解决方案,直到官方SDK支持此< / p>

答案 3 :(得分:1)

此处是带有ILogger的App Insights的documentation。对我来说,它起作用了,但是却有大量的跟踪日志,因此建议您应用自定义过滤器:

builder.AddApplicationInsights("ikey");

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

答案 4 :(得分:0)

现在使用Microsoft.Extensions.Logging.ApplicationInsights提供程序提供了一流的登录到Application Insights的支持。