Skip to content

Instantly share code, notes, and snippets.

@xt0rted
Last active February 3, 2021 14:41
Show Gist options
  • Save xt0rted/0a92c2cd1389a9d5bf1501a22ea83d58 to your computer and use it in GitHub Desktop.
Save xt0rted/0a92c2cd1389a9d5bf1501a22ea83d58 to your computer and use it in GitHub Desktop.
Entity Framework exception telemetry for Application Insights
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);
}
}
}
}
@panuoksala
Copy link

telemetry.Context.Properties is deprecated in latest AI and should be replaced with GlobalProperties.

@marklagendijk
Copy link

marklagendijk commented Feb 3, 2021

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