Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Application Insights with ILoggerFactory

I'm trying to log exceptions to Application Insights. I succeeded in doing this by calling TelemetryClient.TrackException directly. However, I would like to abstract away from this in my code in case I'd want to log to other platforms in the future, so I would like to stick to only the ILogger interface.

I found that you can use ILoggerFactory.AddApplicationInsights (as implemented here) but no matter what I did, I don't see the logs showing up in ApplicationInsights with this.

Below is my code:

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 ... )
    }

Then, I try to use this in my controller like this:

    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" );
    }

However, I don't see any exceptions associated with the request at all. If I replace the Logger.LogError line with TelemetryClient.TrackException (and create the TelemetryClient first), then I can see the exception without any issues.

I don't know what I'm doing wrong. Could anyone help?

like image 830
KangarooWest Avatar asked Jul 10 '17 22:07

KangarooWest


People also ask

How do you integrate application Insights in Azure?

In your function app, select Configuration under Settings, and then select Application settings. If you see a setting named APPINSIGHTS_INSTRUMENTATIONKEY , Application Insights integration is enabled for your function app running in Azure.

How do I add application Insights to web API?

Add Application Insights automatically From within your ASP.NET web app project in Visual Studio: Select Project > Add Application Insights Telemetry > Application Insights Sdk (local) > Next > Finish > Close.


1 Answers

According to your description, I suggest you could try below codes to enable ILogger log the error to the ApplicationInsights.

You could directly use loggerFactory.AddApplicationInsights() method to enable the ApplicationInsights ILogger.

More details, you could refer to below codes:

The startup class:

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?}");
        });
    }
}

The appsettings.json:

{

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

Result:

enter image description here

enter image description here


Update:

The record find in the search feature.

enter image description here

like image 190
Brando Zhang Avatar answered Sep 21 '22 06:09

Brando Zhang