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?
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 thenew 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
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:3. After that, you need to log error in the new class or in any specified code:
4. Test Result: