Alerts for exceptions in an Azure worker role

2019-05-27 11:42发布

问题:

Is there an easy way to send an alert or notification in the Azure Management portal if a worker role throws an exception or has an error?

I am using Azure 2.5

I have tracing and diagnostics all set up and can view the logs in the server explorer of Visual studio, but is there anyway to set an alert if for example and error message appears in the logs.

I know you can set up alerts for monitoring metrics in the Management portal is there an easy way to add metrics for errors and exceptions?

Or someway to get C# exception code to create notifications or alerts in the Azure Management portal?

回答1:

I use SendGrid for sending emails through Azure because it's free. Here is what I would do something like below:

try
{
     //....
}
catch(Exception ex)
{
     MailMessage mailMsg = new MailMessage() {
                //Set your properties here
            };

     // Add the alternate body to the message.
     mailMsg.AlternateViews.Add(
            AlternateView.CreateAlternateViewFromString(Body
                   , new System.Net.Mime.ContentType("text/html")));

     SmtpClient smtpClient = new SmtpClient(
                                 ServerGlobalVariables.SmtpServerHost
                                 , Convert.ToInt32(587));

     System.Net.NetworkCredential credentials = 
          new System.Net.NetworkCredential(
                 ServerGlobalVariables.SmtpServerUserName
                 , ServerGlobalVariables.SmtpServerPassword);

     smtpClient.Credentials = credentials;

     smtpClient.Send(mailMsg);
}

Please note that I store my credits in a globalvariables class called ServerGlobalVariables. Also, I send my emails formatted as HTML, but you don't have to do that.

Let me know if you have any questions. ~Cheers



回答2:

I ended up using email alerts and Application insights to monitor my worker role in the Azure portal. I created an Application insight on the portal according to these instructions.

Using the Nuget package manager in Visual Studio I added the Application insights API, Application insights for website (even though my worker role is not a web app) and the Application insights trace listener.

I then created an Application insight instance by adding the following to the worker role.

private TelemetryClient tc = new TelemetryClient();

And then adding this to the onStart method.

        tc.Context.InstrumentationKey = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXX";

You can find your insturmentation Key in the Azure Portal.

After running, or deploying my worker role I could then view all of my Trace.TraceInformation and TraceError statements in the Azure portal as well as add tc.TrackError and tc.TrackEvent statements to track errors and events.

TrackError worked perfectly for notifying me when an exception was thrown.