使用ILoggerFactory与Application Insights

15

我想将异常记录到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<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个回答

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

结果:

输入图像描述

输入图像描述


更新:

在搜索功能中找到的记录。

输入图像描述


谢谢。不过,我尝试了这个方法,但仍然没有起作用。为了确保我尝试的是正确的事情 - 您的答案与我在问题中已经发布的内容有何不同,以便我可以进行正确的编辑?另外,如果有帮助的话, 1)我尝试添加AddAzureWebAppDiagnostics(),我可以看到日志流,所以我认为我正在正确使用Logger。 2)我可以直接使用TrackException并在ApplicationInsights上查看结果,所以我认为我正在正确设置appSettings.json。这就是为什么我感到困惑,为什么事情仍然不起作用 :| - KangarooWest
1
我建议您可以重新检查您的AI记录。据我所知,log.error意味着在AI中添加跟踪记录,因此您将无法在失败中找到记录,但您可以在跟踪记录中找到它。如我的回答更新所示,建议您通过搜索按钮(在AI门户网站中)重新检查记录。 - Brando Zhang
感谢Brando的建议。我最终解决了问题。我猜测我们的代码使用了不同版本的NuGet包,这些包一直在快速发展,因此导致了不同的行为。 - KangarooWest
4
但真正的问题是......如何在带有 ilogger 的 core 2.0 控制台应用程序中启用 Application Insights? - Reft
loggerFactory.AddApplicationInsights - Dainius Kreivys

5

这应该是开箱即用的,但似乎我漏掉了什么,因为它没有记录跟踪。以下是否足够? services.AddApplicationInsightsTelemetry(); - tonycdp
您可能需要检查日志级别过滤器,因为默认情况下会过滤掉所有比信息级别更“冗长”的消息。 - James
当我执行以下操作时: _logger.LogTrace("Logging trace"); _logger.LogDebug("Logging debug"); _logger.LogInformation("Logging info"); _logger.LogWarning("Logging warning"); _logger.LogError("Logging error"); _logger.LogCritical("Logging critical"); 我可以在控制台上看到输出,但在AI跟踪中没有任何输出。 - tonycdp
你解决了这个问题吗,@tonycdp?我也遇到同样的问题,没什么帮助。 - Piedone
@Piedone 是的,这是一个配置问题。建立一个虚拟应用程序并与您所拥有的进行比较。抱歉我不能提供更多帮助,因为已经过了一段时间。 - tonycdp
谢谢,没关系。我也试过了 :). - Piedone

4
我终于明白了。解决我的问题有两种方法:
简单的方法: 我使用Application Insights NuGets的旧版本,具体来说是Microsoft.ApplicationInsights.2.2.0和Microsoft.ApplicationInsights.AspNetCore.2.0.0。 一旦升级到Microsoft.ApplicationInsights.2.4.0和Microsoft.ApplicationInsights.AspNetCore.2.1.1,一切都按预期工作。您还会看到LogXXX作为参数的异常显示为Exception,没有异常的显示为Trace,正如预期的那样。
稍微困难一些的方法: 由于某种原因,在Configure中的IApplicationBuilder和IServiceProvider不提供正确的服务提供程序以在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中的错误。我还希望看到跟踪和异常,这是新包版本才有的功能。

2
不幸的是,SDK最近才更新,只能触发异常遥测(见commit),但这个变化还没有发布。
现在我能看到的唯一途径就是要么保留你代码中显式调用的TelemetryClient.TrackException,要么用自己实现的ILogger包装它们 - 这两种方法都只是临时解决方案,直到官方SDK支持此功能。

从提交记录来看,当出现异常时,它似乎会触发ExceptionTelemetry;否则触发TraceTelemetry。这也是我在我的代码测试中得到的结果。您是在暗示他们以后会删除TraceTelemetry吗? - KangarooWest
我的意思是,在当前的SDK中,它们只支持TraceTelemetry。将来的SDK版本中将提供触发ExceptionTelemetry的能力。 - EranG

1

这里是使用ILogger的App Insights的文档。对我来说它很有效,但是会产生大量跟踪日志,建议您应用自定义过滤器:

builder.AddApplicationInsights("ikey");

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接