Last active
February 3, 2021 14:41
-
-
Save xt0rted/0a92c2cd1389a9d5bf1501a22ea83d58 to your computer and use it in GitHub Desktop.
Entity Framework exception telemetry for Application Insights
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Data.Entity.Validation; | |
using System.Linq; | |
using Microsoft.ApplicationInsights.Channel; | |
using Microsoft.ApplicationInsights.DataContracts; | |
using Microsoft.ApplicationInsights.Extensibility; | |
public class EntityFrameworkExceptionTelemetryInitializer : ITelemetryInitializer | |
{ | |
public void Initialize(ITelemetry telemetry) | |
{ | |
if (!(telemetry is ExceptionTelemetry exceptionTelemetry)) | |
{ | |
return; | |
} | |
if (exceptionTelemetry.Exception is DbEntityValidationException dbException) | |
{ | |
var validationErrors = dbException.EntityValidationErrors.ToArray(); | |
for (var i = 0; i < validationErrors.Length; i++) | |
{ | |
var error = validationErrors[i]; | |
// keys need to be unique | |
var key = $"{error.Entry.Entity}[{i}]"; | |
var value = string.Join("; ", error.ValidationErrors.Select(e => $"{e.PropertyName}: {e.ErrorMessage}")); | |
telemetry.Context.Properties.Add(key, value); | |
} | |
} | |
} | |
} |
using System.ComponentModel;
using System.Data.Entity.Validation;
using System.Linq;
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Extensibility;
using MoreLinq;
public class EntityFrameworkExceptionTelemetryInitializer : ITelemetryInitializer
{
[Localizable(false)]
public void Initialize(ITelemetry telemetry)
{
if (!(telemetry is ExceptionTelemetry exceptionTelemetry) ||
!(exceptionTelemetry.Exception is DbEntityValidationException dbException))
{
return;
}
dbException.EntityValidationErrors.ForEach((error, index) =>
{
var key = $"{error.Entry.Entity}[{index}]";
var value = string.Join("; ", error.ValidationErrors.Select(e => $"{e.PropertyName}: {e.ErrorMessage}"));
telemetry.Context.GlobalProperties.Add(key, value);
});
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
telemetry.Context.Properties is deprecated in latest AI and should be replaced with GlobalProperties.