Logging errors to AppTraces instead of AppExceptions?

778 Views Asked by At

I have an azure function app that uses the microsoft extension logging to application insigths.

I have this code:

public static void Run(IService service, ILogger log, bool throwException, bool addHeartBeat = false)
{
    try
    {
        if (addHeartBeat)
        {
            var props = new Dictionary<string, object> { {"IsHeartBeat",true } };
            log.LogMetric($"Heartbeat: {service.GetType().ToString()}", 0, props);
        }

        log.LogInformation($"{{logTypeStart}}: {service.GetType()}", logTypeStart);
        service.Run(log);
        log.LogInformation($"{{logTypeEnd}}: {service.GetType()}", logTypeEnd);
    }
    catch (Exception ex)
    {
        log.LogCritical(ex, ex.Message);

        if (throwException)
        {
            throw ex;
        }
    }
}

I would expect LogCritical to log to the Exceptions but it is added to AppTraces. Can this be changed to log to Exceptions instead?

1

There are 1 best solutions below

0
On

To log the error as Exception in app insights, this line of code _logger.LogError("Test", new Exception("Test")); should be changed to _logger.LogError(new Exception(), "test");, which means the new Exception() should be the first parameter.

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

enter image description here

My Repro 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. After that, you need to log error in the new class or in any specified code:

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:

enter image description here