Monitor Azure Functions
Learn how to monitor your Azure Functions to ensure they are running efficiently and to troubleshoot issues.
Introduction to Monitoring
Effective monitoring is crucial for maintaining the health, performance, and reliability of your Azure Functions applications. Azure provides a comprehensive suite of tools and services to help you gain insights into your functions' execution, track performance metrics, and diagnose potential issues.
Key aspects of monitoring include:
- Logging: Capturing detailed information about function execution.
- Metrics: Tracking performance indicators like execution count, duration, and error rates.
- Alerting: Setting up notifications for critical events or performance degradation.
- Tracing: Understanding the flow of requests across distributed systems.
Leveraging Application Insights
Application Insights is an extensible Application Performance Management (APM) service for web developers. It's used to detect, diagnose, and triage issues from the perspective of your users. It can automatically detect application anomalies, and includes powerful analytics tools to help you diagnose issues and understand what users of your app are doing.
- Live Metrics: Real-time monitoring of requests, failures, and server response times.
- Failures: Detailed analysis of exceptions and failed requests.
- Performance: Insights into function execution times and dependencies.
- Operations: Visualizing the flow of operations across your functions.
- Logs (Analytics): Querying telemetry data using Kusto Query Language (KQL).
To integrate Application Insights with your Azure Functions, you typically configure an Application Insights instrumentation key in your function app's application settings.
Example configuration in host.json:
{
"version": "2.0",
"logging": {
"applicationInsights": {
"samplingSettings": {
"isEnabled": true,
"excludedTypes": "Request"
}
}
}
}
And setting the instrumentation key as an application setting: APPINSIGHTS_INSTRUMENTATIONKEY.
Diagnostic Logging
Azure Functions provides built-in logging capabilities. You can write logs from within your function code using a logging abstraction provided by the Functions host. These logs are sent to Application Insights or other configured log destinations.
You can log various types of information:
- Information: General execution details.
- Warnings: Potential issues that don't prevent execution but may indicate problems.
- Errors: Exceptions and critical failures.
- Information: Custom debugging information.
Logging in C#
using Microsoft.Extensions.Logging;
public static class MyFunction
{
[FunctionName("MyFunctionName")]
public static void Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, ILogger log)
{
log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
// ... function logic ...
log.LogWarning("This is a warning message.");
try
{
throw new Exception("Simulated error.");
}
catch (Exception ex)
{
log.LogError(ex, "An error occurred during function execution.");
}
}
}
Logging in JavaScript
module.exports = async function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');
const name = (req.query && req.query.name) || (req.body && req.body.name);
const responseMessage = name ?
"Hello, " + name + ". This HTTP triggered function executed successfully." :
"This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.";
context.log.warn('This is a warning message.');
try {
throw new Error('Simulated JavaScript error.');
} catch (error) {
context.log.error('An error occurred: ' + error.message);
}
context.res = {
status: 200,
body: responseMessage
};
};
Monitoring Metrics
Azure Monitor provides metrics for your Azure Functions. These metrics offer insights into the performance and operational health of your function apps.
- Function Execution Count: The total number of times your functions have executed.
- Function Execution Units: Measures the compute resources consumed by function executions (relevant for Consumption plan).
- Memory Working Set: The amount of physical memory the function app is using.
- HTTP 5xx: The number of server-side errors (5xx).
- HTTP 4xx: The number of client-side errors (4xx).
- Queue Length: For queue-triggered functions, the current length of the queue.
You can view these metrics in the Azure portal under your Function App's "Monitoring" section or directly within Azure Monitor.
Setting Up Alerts
Azure Monitor Alerts allow you to proactively notify yourself or automate responses when specific conditions are met based on metrics or logs. This is essential for detecting and responding to issues before they impact users.
To set up an alert:
- Navigate to your Function App in the Azure portal.
- Go to the "Monitoring" section and select "Alerts".
- Click "Create alert rule".
- Define the scope, condition (metric or log query), and action group (what happens when the alert fires, e.g., send an email, trigger a webhook).
Troubleshooting Common Issues
When issues arise, several tools can help you diagnose the root cause:
- Azure Portal Logs: Directly view logs generated by your functions.
- Application Insights "Failures" blade: Drill down into exceptions and failed operations.
- Application Insights "Performance" blade: Identify slow-performing functions or dependencies.
- Kusto Query Language (KQL): For advanced analysis of telemetry data stored in Application Insights.
Example KQL Query for Errors
requests
| where success == false
| project timestamp, name, url, resultCode, duration
| order by timestamp desc
- Insufficient Logging: Not logging enough detail makes troubleshooting difficult.
- Ignoring Warnings: Warnings can be early indicators of future problems.
- Cold Starts: For Consumption plan, long cold starts can impact performance. Monitor execution duration.
- Concurrency Limits: Be aware of function app limits to avoid throttling.