ASP.NET Core + ApplicationInsights Logging Errors as Trace

If you want to log the error as Exception in app insights, this line of code _logger.LogError("Test", new Exception("Test")); should be changed.

Change it to _logger.LogError(new Exception(), "test");, which means the new Exception() should be the first paramter.

And you can add application insights SDK by right click your project -> add -> Application Insights Telemetry, which is very useful doing some thing automatically(ie. adding .UseApplicationInsights() in Programs.cs): enter image description here

I also post my test steps:

1.Adding application insights SDK as mentioned above

2.Add loggerFactory.AddApplicationInsights(app.ApplicationServices,LogLevel.Information); in Startup.cs -> Configure() method, code as below:

            public void Configure(IApplicationBuilder app, IHostingEnvironment env,ILoggerFactory loggerFactory)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseExceptionHandler("/Error");
                    app.UseHsts();
                }

                app.UseHttpsRedirection();
                app.UseStaticFiles();
                app.UseCookiePolicy();

                app.UseMvc();

                //Add this line of code
                loggerFactory.AddApplicationInsights(app.ApplicationServices,LogLevel.Information);
            }

3.Then in somewhere you wanna log error:

        public class AboutModel : PageModel
        {
            private ILogger _logger;

            public AboutModel(ILogger<AboutModel> logger)
            {
                _logger = logger;
            }

            public string Message { get; set; }

            public void OnGet()
            {
                _logger.LogInformation("it is just a test herexxxx");

               //Only this format can log as exception
                _logger.LogError(new Exception(), "it is a new Exceptionxxxx");

               //it will log as trace
                _logger.LogError("error logs xxx");
                Message = "Your application description page.";
            }
        }

4.Test result as below: enter image description here


Since Microsoft.ApplicationInsights.AspNet v2.7 the question and the accepted answer are outdated, as calling AddApplicationInsights on ILoggerFactory is now obsolete.

Please refer to the official docs.

The gist from the docs:

  1. ApplicationInsightsLoggerProvider is enabled by default.
  2. Captured log types can be configured in appsettings.json (or programmatically if you really need it)
    "Logging": {
        "LogLevel": {
            "Default": "Warning"
        },
        "ApplicationInsights": {
            "LogLevel": {
                "Default": "Error"
            }
        }
    }