I need to set an azure alert to my azure function http triggered. When I have an internal server error (500) then I need to send an alert email to a group of emails.
How to create a azure dash board to get the number of hits to an API.
need a better solution for alert email template and alerts setting.
I Tried to reproduce the same in my environment to create azure alerts when the function gets HTTP 500 server error:
Azure alert when azure function http triggered.
I have created a function app, like below.
Azure portal > Function App >Create
Create a function with visual studio and upload the same to the function app.
Sample code to create an exception.
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
throw new Exception("An error has occurred.");
}
Once publish the code to Azure Function app, check the Function Status. Like below.
Azure Portal > Function App > Select your Function app >Functions.
Run the function and check the result, like below.
Open Functions >Code + Test > Test/Run
Note: Body section add above vs code to get 500 server error.
Output
To generate the alert for HTTP 500 error.
Functions > Monitor > Run query in Application Insights
Query to check 500 internal error.
requests
| project
timestamp,
id,
operation_Name,
success,
resultCode,
duration,
operation_Id,
cloud_RoleName,
invocationId=customDimensions['InvocationId']
| where timestamp > ago(30d)
| where cloud_RoleName =~ 'httpdtriggeredfunc01' and operation_Name =~ 'Function1'
| order by timestamp desc
| take 20
Click on a new alert rule to generate the alert for the same error.
Create an action group with your DL email id.
When the function triggered HTTP 500 internal server error, you will get an alert to your mail id.
Successfully received an email.
2. How to create an azure dashboard to get the number of hits to an API.
To create a dashboard for the function app.
Open your function app > Application Insights > View Application Insights data.
Once open the application Insights data and select the application dashboard option, it will create a dashboard for your function app automatically.
Related
There is one requirement to send an email upon unsuccessful web-jobs only. There are 16 web-jobs which are deployed and running successfully on azure portal. I have suggested to modify the code for existing web-job but client does not want to modify web-jobs. He wants to add something extra which does not require to modify web-jobs anymore. I am confused, without modifying web-jobs, how can I send an email? I searched a lot on google and stack-overflow but didn't get anything.
How can I implement this?
Few of the workarounds for getting the notification to email for WebJobs Status:
Using ErroTrigger and SendGrid extensions. you can do the Notifications sending to email for the WebJob SDK.
check this article on how to set that up which uses both extensions to send an email if an error occurred 10 times in 30 minutes window with a throttle up to 1 hour.
public static void ErrorMonitor(
[ErrorTrigger("0:30:00", 10, Throttle = "1:00:00") TraceFilter filter,
[SendGrid] SendGridMessage message)
{
message.Subject = "WebJobs Error Alert";
message.Text = filter.GetDetailedMessage(5)
}
If you aren't using the WebJob SDK, then unfortunately there aren't any events for continuous webjobs. There is only one for triggered jobs.
Also, visit this MSFT Doc and SO Thread for information on setting up the email alerts with App Services.
I am trying to fetch invocation id of an Azure Function using the app insights query:
requests
| project
id,
operation_Name,
operation_Id,
cloud_RoleName,
invocationId=customDimensions['InvocationId']
| where cloud_RoleName =~ 'appname' and operation_Name =~ 'Gen'
And The result table shows no value for invocation id:
Am I missing something? Please let me know in the comment If I can add more information. Thanks.
I tried to reproduce your issue as I have got the invocation Id in the logs by following the below steps:
Created the Function App (.Net Core 6 Stack) in Azure with the HTTP Trigger Function Class inside the Azure Portal.
Open the Function App> Click on Logs in Monitoring Menu (left index pane) > Close this dialog box
Copied your query to get the results, where in the query:
cloud_RoleName is given as FunctionAppName,
operation_Name is given as FunctionName.
I have timer triggered Function. It is executed every minute but I don't see any logs in Monitor section in Azure Portal.
However when I click "Run query in Application Insights" and fix cloudRoleName in query (by default it is set to name of application but we changed it with ITelemetryInitializer) it displays all executions correctly.
EDIT:
This is my startup code
public class Startup : IWebJobsStartup
{
public void Configure(IWebJobsBuilder builder)
{
builder.Services
.AddSingleton<ITelemetryInitializer, CloudRoleNameInitializer>();
// more registrations
}
and CloudRoleNameInitializer
public class CloudRoleNameInitializer : ITelemetryInitializer
{
public void Initialize(ITelemetry telemetry)
{
telemetry.Context.Cloud.RoleName = "EmailPuller";
}
}
When I click run query in application Insights the query generated is
requests
| project timestamp, id, operation_Name, success, resultCode, duration, operation_Id, cloud_RoleName, invocationId=customDimensions['InvocationId']
| where timestamp > ago(30d)
| where cloud_RoleName =~ 'emailpuller-UNIQUE_ID_FROM_ARM_TEMPLATE' and operation_Name =~ 'OurOperationName'
| order by timestamp desc
| take 20
So you can see cloud_RoleName is different than set by ITelemetryInitializer. If I update query to use 'emailpuller' it returns information on executions
Your guess is right. The Monitor UI uses the default CloudRoleName to query the logs.
It's easy to find the root cause. The steps are as below:
1.Nav to azure portal -> your azure function -> Monitor -> press F12 to open the Develop Tool of the browser.
2.then click the Refresh button -> then in the Develop tool, select the api -> then in the Request Payload, you can see this api uses the default CloudRoleName to query the logs.
Here is the screenshot:
This may be a bug, you can raise an issue in github of Azure function.
I have some error alerts in a prod env that I would like to be alerted for if they fire. The issue is that they have never fired so I cannot see them in the portal.
Thanks!
I think I now better understand your issue. Today I was notified using this post of a new capability:
Define an alert rule on a custom metric that isn't emitted yet
When creating a metric alert rule, the metric name is validated against the Metric Definitions API to make sure it exists. In some cases, you'd like to create an alert rule on a custom metric even before it’s emitted. For example, when creating (using an Resource Manager template) an Application Insights resource that will emit a custom metric, along with an alert rule that monitors that metric.
To avoid having the deployment fail when trying to validate the custom metric’s definitions, you can use the skipMetricValidation parameter in the criteria section of the alert rule, which will cause the metric validation to be skipped.
(source)
I see you have a try/catch, then you can consider sending a custom error message to application insights(the logic here is that since you know the custom error message, you can use this pre-defined message to create an alert), by using the code below in your catch block:
try
{
//your code
}
catch
{
//if you're using ILogger which is integrated with application insights.
_logger.LogError(new Exception(),"custom error: xxxx");
//your other code
}
Then nav to azure portal -> the application insights -> Logs:
1.Write the query like below:
exceptions
| where customDimensions.FormattedMessage == "custom error: xxxx"
2.Select the query, and click the run button.
3.At last, click the "New alert rule" button to create the alert.
I have scheduled my console application as a web job in azure portal.
how to get azure web job running alert in mail from azure portal that whether it runs successfully or any failure occurred.
how to get azure web job running alert in mail from azure portal that whether it runs successfully or any failure occurred.
I haven't found any way to do it on Azure portal. You could modify your code to implement it.
As one of my original posts mentioned, WebJobs status depends on whether your WebJob/Function is executed without any exceptions or not. I suggest you put all your code in a try code block. If any exception throws, it means the status of this run will be failure. Otherwise the status will be success.
try
{
//Put all your code here
//If no exception throws, the status of this run will be success
//Send success status to your mail
}
catch
{
//If any exception throws, the status of this run will be failure
//Send failure status to your mail
}
To send a mail in your WebJob, you could use SendGrid component or any other SMTP client library. Here is a sample of using SmtpClient to send mail from hotmail.
MailMessage mail = new MailMessage("frommail#hotmail.com", "tomail#hotmail.com");
SmtpClient client = new SmtpClient();
client.Port = 587;
client.EnableSsl = true;
client.Credentials = new NetworkCredential("frommail#hotmail.com", "mail_password");
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Host = "smtp.live.com";
mail.Subject = "this is a test email.";
mail.Body = "this is my test email body";
client.Send(mail);
I wasn't able to find a way to send emails on job run or even failure using only "pure" azure tools (without me writing any code). However, what you can do is use Kudu Web Hooks for job completion: https://github.com/projectkudu/kudu/wiki/Web-hooks (Kudu is part of Azure).
For example, you can create another web job or a function with an HTTP trigger which will run on each web hook call, will check job completion status, and will send emails on failure. Thus, you can have single web job handling errors of all other web jobs you have.
Web UI for configuring web hooks is at https://your_web_app_name.scm.azurewebsites.net/WebHooks, and you can find the model of the web hook message body here: https://github.com/projectkudu/kudu/blob/master/Kudu.Contracts/Jobs/TriggeredJobRun.cs.