Monitoring Azure function - azure

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.

Related

how to add azure alerts when we get server error

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.

How to add custom properties to HTTPS calls so I can see them in Azure Application Insights?

I have a C# client application that calls a web application in Azure (also in written in C#, ASP .NET Core). Traffic gets captured in Azure Log Analytics so I can see it in Azure Application Insights.
When calling the web application from my client application, I would like to add some information about the version of the client application. I want this information to be easily viewable in Application Insights.
I notice that the requests table in Application Insights has a column called customDimensions. Maybe I can put stuff there, but I don't know how.
My idea is to add this information as a header and somehow configure the application to copy this information from the header into customDimensions. Is this a good way to go? If so, how do I accomplish the latter half (configure the application to copy this information from the header into customDimensions)?
You could write a telemetry initializer for this, as explained in the docs:
Use telemetry initializers to enrich telemetry with additional information or to override telemetry properties set by the standard telemetry modules.
There is a base class (TelemetryInitializerBase) that you can use which provides access to the http context to get details of the headers:
public class CustomInitializer : TelemetryInitializerBase
{
public CustomInitializer(IHttpContextAccessor contextAccessor) : base(contextAccessor)
{
}
protected override void OnInitializeTelemetry(HttpContext platformContext, RequestTelemetry requestTelemetry, ITelemetry telemetry)
{
var appVersion = platformContext.Request.Headers["x-app-version"].ToString();
if(!string.IsNullOrWhiteSpace(appVersion))
requestTelemetry.Properties["appVersion"] = appVersion;
}
}
Add this initializer to the web app running in Azure. Then, in the customDimensions field of the request telemetry you can find the value of appVersion.
Another option is to set custom propertions in the controller action like this:
var appVersion = Request.Headers["x-app-version"].ToString();
if (!string.IsNullOrWhiteSpace(appVersion))
{
var requestTelemetry = HttpContext.Features.Get<RequestTelemetry>();
requestTelemetry.Properties.Add("appVersion", appVersion);
}

Why is Azure function Invocation Id empty?

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.

Trace Telemetry not showing up on Azure Portal

I have an MVC app running on local IIS server. I have an existing App Insights resource on Azure where I want Telemetry from my app to show up. However, Trace messages are not showing up on Azure Portal. I have added ApplicationInsights to my project, specified the resource where Telemetry should show up in ApplicationInsights.config and also written a TelemetryWrapper that I use in my code to send out the actual Telemetry Info and Error messages.
I initialize the Telemetry service through the wrapper:
TelemetryWrapper.InitializeTelemetry("InstrumentationKey", "ApplicationName");
And send out messages from the wrapper too
TelemetryWrapper.TelemetryInfo(requestId, action, userId, ultimateId, systemId, payload);
An overview of the TelemetryWrapper:
public static void InitializeTelemetry(string apiKey, string appId)
{
bool postBackground = true;
_telemetry = new TelemetryHelper(apiKey, appId, false) { PostBackground = postBackground };
}
public static void TelemetryInfo(Guid requestId, string action, Guid userId, string ultimateId, string systemId,
string payload)
{
var telem = CreateInstance(requestId, action, ultimateId, userId, systemId, payload);
_telemetry.Info(telem);
}
What am I possibly doing wrong?
Need more information. all you've shown is your code, there's no AppInsights code here to look at. so it could be that your TelemetryHelper class isn't setting the ikey correctly, the ikey could be invalid.
However: The one thing that jumps out at me is your usage of the terms apiKey and appId in your code.
Those 2 things have specific meaning in application insights, but that is for reading data from the AI API services (and apiKey in that context is something you could consider a secret, as if someone has those keys they can read all of your data!) I'm not sure if you're using them in a different context here but that jumped out at me right away.
There's a different thing, "Instrumentation Key" or iKey that you use to send data to application insights. Are you possibly switching those things around and trying to use an AI appId and apiKey in place of an iKey?
One way to check is to use fiddler or some other tool locally to watch outbound http traffic. configure it to decrypt https, and watch for outbound calls to dc.services.visualstudio.com, which is where your telemetry is going. If you have outbound calls, then it is at least trying to send your telemetry. If those calls are failing, the response might tell you that the iKey you are using is invalid, if this is the case.
You do not need

How to get the details of a continuous Azure WebJob invocation

Looking at the Kudu Azure WebJobs API docs https://github.com/projectkudu/kudu/wiki/WebJobs-API I see there are several calls I can do to manage WebJobs programmatically.
What is missing is a call to get, for a continuous webjob, the details of a single invocation. With invocation I mean the single execution of the function for a given message.
What I am trying to do is, for a message getting in the poison queue, to get the exception message of the parent invocation. In the poison message I get the id of the parent invocation with the json prop $AzureWebJobsParentId.
I would like to manage the poison queue with a function that emails the details of the error and moves the message in a dead-letter queue.
Any idea if this is possible?
The Azure WebJobs SDK Core extensions contain a binding for ExecutionContext which allows you to access invocation specific system information in your function. An example showing how to access the function Invocation ID:
public static void ProcessOrder(
[QueueTrigger("orders")] Order order,
TextWriter log,
ExecutionContext context)
{
log.WriteLine("InvocationId: {0}", context.InvocationId);
}
The invocation ID is used in the Dashboard logs, so having access to this programatically allows you to correlate an invocation to those logs.
Create a function specific error handler that will only handle errors for one function. This is done by naming convention based on an "ErrorHandler" suffix.
public static void ProcessOrderErrorHandler(
[ErrorTrigger()] TraceFilter filter,
TextWriter log)
{
var lastMessage = filter.Message;
var lastMessages = filter.GetDetailedMessage(5);
}
For email notifications
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);
}
There's not an official way to do this yet, but there's an issue to track exposing stable APIs (C# and REST) for reading the individual function instances: See https://github.com/Azure/azure-webjobs-sdk/issues/880 for status
Given a WebJobs SDK invocation ID, you can access the details of that execution via the WebJobs Dashboard. You can access the Dashboard via the WebJobs blade in the portal (the link will be in the "LOGS" column).
Or in the browser you can form the URL yourself, for example (substituting your app name and invocation ID):
https://<yourapp>.scm.azurewebsites.net/azurejobs/#/functions/invocations/<invocation-id>
That is how you would access these details manually.

Resources