Using Application Insights with ILoggerFactory

后端 未结 5 1947
攒了一身酷
攒了一身酷 2020-12-31 08:44

I\'m trying to log exceptions to Application Insights. I succeeded in doing this by calling TelemetryClient.TrackException directly. However, I would like to ab

5条回答
  •  离开以前
    2020-12-31 09:18

    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:


    Update:

    The record find in the search feature.

提交回复
热议问题