skip to Main Content

I’m currently using Sendgrid to send all my users pretty formatted emails on specific events they perform on my site (ex. creating a login, adding credit cards, etc) and I’m doing this with an email service I created that uses Sendgrid (subscription through my Azure portal). I’m also using the .Net logger service and thought I could get email notifications through that, but I don’t really see anything in my Azure portal.

QUESTION – What if my website throws an exception like the example below, what’s the best way to get notified?

  1. Use my email service to send out an email to myself? or
  2. Use some Azure settings to send out an email?

Here is an example from server side and what I currently do, which is send myself an email with Sendgrid, but it seems like it might not be the best solution.

 try {
     // perform some action and save to db
 } catch(Exception ex) {
     _logger.LogError(ex, "Error: " + ex.ToString());
     _emailService.SendEmailError("Some Exception", ex.ToString());
 }

UPDATE – Based on Peter Bons post below – I have application insights up and running and I can see some data coming in. I then created an action group ("notify") and configured it to send me an email. I received some notification from Azure saying it’s configured, so all is good. Next I tried creating an alert in my apps application alert panel, but got confused as to which type of signal I needed to select for logging. I tried creating 2 different alerts, 1 on "exceptions" under metrics and 1 on "All Administrative Operations" under Activity Log. Once these 2 alerts were working I started to receive emails. BUT I started receiving lots of emails and Azure shut me down due to rate limits, so now I have some questions:

  1. Where do I create the alert? I see 2 separate places where it can be created 1.) app service alerts 2.) app service application insight alerts. No events seem to be fired in the application insights alert section, only in the app alert section.

  2. What type of signal do I select that will get triggered when I log information (ex. _logger.LogError()), because even when I create an alert that is based on any admin event using verbose (so tons of alert triggers and created with tons of emails) There is no event fired and email for the logger calls!

2

Answers


  1. You can use Azure Application Insights to capture exceptions from your ASP.NET app along with request telemetry.

    Thanks to Regan Downer, for the Send notification.
    You can insert code in your application to call Microsoft.ApplicationInsights.TrackTrace(). Send the POST data in the message parameter.

    You can log exceptions explicitly by inserting code in exception handlers to report the exceptions.

    enter image description here

    Create an Azure Function that sends an email using SendGrid.

    In your ASP.NET Core app, add the following code to your Startup.cs file to configure Application Insights.

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddApplicationInsightsTelemetry();
        }
    
    

    In your ASP.NET core app, add the following code to your Configure method in Startup.cs to enable Application Insights exception tracking:

       app.UseExceptionHandler(errorApp =>
        {
            errorApp.Run(async context =>
            {
                var exception = context.Features.Get<IExceptionHandlerFeature>().Error;
                var telemetry = new TelemetryClient();
                telemetry.TrackException(exception);
                await context.Response.WriteAsync("An error occurred and has been logged.");
            });
        });
    

    This code will catch any unhandled exceptions in your app and log them to Application Insights.

    And you can then use the Azure Function you created to send an email notification when an exception is logged in Application Insights.

    Capture exceptions from Azure Application Insights.

        using Microsoft.ApplicationInsights;
        using Microsoft.ApplicationInsights.Extensibility;
    
    public class MyClass
    {
        private readonly TelemetryClient _telemetryClient;
    
        public MyClass()
        {
            var telemetryConfiguration = TelemetryConfiguration.CreateDefault();
            telemetryConfiguration.InstrumentationKey = "YOUR_INSTRUMENTATION_KEY";
            _telemetryClient = new TelemetryClient(telemetryConfiguration);
        }
    
        public void MyMethod()
        {
            try
            {
                // Perform some action
            }
            catch (Exception ex)
            {
                _telemetryClient.TrackException(ex);
            }
          }
        }
    

    For further information refer to the MSDoc.

    To send notification email with the application insights logs.

    using var channel = new ServerTelemetryChannel();
                try
                {
                    IServiceCollection services = new ServiceCollection();
                    services.Configure<TelemetryConfiguration>(
                        config =>
                        {
                            config.TelemetryChannel = channel;
                            // Optional: implement your own TelemetryInitializer instance and configure it here
                            // config.TelemetryInitializers.Add(new MyTelemetryInitializer());
                            config.DefaultTelemetrySink.TelemetryProcessorChainBuilder.UseSampling(5);
                            channel.Initialize(config);
                        });
                    services.AddLogging(builder =>
                    {
                        // Only Application Insights is registered as a logger provider
                        builder.AddApplicationInsights(
                            configureTelemetryConfiguration: (config) => config.ConnectionString = "<YourConnectionString>",
                            configureApplicationInsightsLoggerOptions: (options) => { }
                        );
                    });
                    IServiceProvider serviceProvider = services.BuildServiceProvider();
                    ILogger<Program> logger = serviceProvider.GetRequiredService<ILogger<Program>>();
                    logger.LogInformation("Logger is working...");
                }
                finally
                {
                    // Explicitly call Flush() followed by Delay, as required in console apps.
                    // This ensures that even if the application terminates, telemetry is sent to the back end.
                    channel.Flush();
                    await Task.Delay(TimeSpan.FromMilliseconds(1000));
                }
    
    Login or Signup to reply.
  2. Add Azure Application Insights to the mix using this tutorial as a starting point and use the alerts feature.

    Once properly done, code like this _logger.LogError(ex, "Error: " + ex.ToString()); will generate an Exception Telemetry item in Application Insights as documented here:

    ApplicationInsightsLoggerProvider captures ILogger logs and creates TraceTelemetry from them. If an Exception object is passed to the Log method on ILogger, ExceptionTelemetry is created instead of TraceTelemetry.

    Once there, you can create an alert rule based on critera, like an exception has occured. An alert rule has one or more action groups attached. Those action groups define what action is taken once an alert rule is triggered. An example action is to send an email.

    The nice thing about using alert rules and action rules is that the way the alerts are triggered and the action that take place when that happens is that the code that makes an alert rule being triggered, for example _logger.LogError(ex, "Error: " + ex.ToString()), is decoupled from whatever happens next. If you need to change the email address, want to include different actions like sending SMS or trigger a webhook you can do so withouth modifying any code.

    A complete tutorial can be found here

    Now regarding your two other questions:

    Where do I create the alert? I see 2 separate places where it can be created 1.) app service alerts 2.) app service application insight alerts. No events seem to be fired in the application insights alert section, only in the app alert section.

    There are many places you can start defining alerts. You can even create one from the Azure Monitor resource. If you do that you need to drill down to the resource that is the source of your alert rule.

    When choosing the app service application insight alerts you already drilled down to the right resource so that is the best place to start.

    What type of signal do I select that will get triggered when I log information (ex. _logger.LogError()), because even when I create an alert that is based on any admin event using verbose (so tons of alert triggers and created with tons of emails) There is no event fired and email for the logger calls!

    First of all, do not use any of the signal of the Activity Log section. Those signals indicate something is changed to the resource itself, like an Application Insights setting is updated or an Web App is scaled up.

    To create an alert rule for logs generated by _logger.LogXXX() use the Custom log search signal, see your other question.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search