ASP.NET Core + ApplicationInsights Logging Errors as Trace

11,254

Solution 1

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

Solution 2

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"
            }
        }
    }
Share:
11,254
TheWebGuy
Author by

TheWebGuy

.NET developer

Updated on June 17, 2022

Comments

  • TheWebGuy
    TheWebGuy almost 2 years

    I am using Microsoft.ApplicationInsights.AspNetCore (https://www.nuget.org/packages/Microsoft.ApplicationInsights.AspNetCore).

    I've enabled application insights by adding .UseApplicationInsights() in Programs.cs and in my startup class:

        loggerFactory.AddApplicationInsights(app.ApplicationServices);
    

    This all works fine, I am able to see requests in app insights but when I try to log an error (for example in my controller):

            _logger.LogError("My Error Log");
            _logger.LogError("Test", new Exception("Test"));
    

    Both are logged as trace events and not exceptions in app insights.

    How do I make it so it logs as an exception?

  • TheWebGuy
    TheWebGuy over 5 years
    Thank you this was very helpful!
  • Justin
    Justin over 3 years
    loggerFactory.AddApplicationInsights(app.ApplicationServices‌​,LogLevel.Informatio‌​n); is now obsolete at least on .Net 5.