Monitoring Azure Functions
Last updated: May 15, 2024
Monitoring your Azure Functions is crucial for understanding performance, diagnosing issues, and ensuring the reliability of your serverless applications. Azure provides several integrated tools and services to help you monitor your functions effectively.
Key Monitoring Tools
The primary services you'll use for monitoring Azure Functions are:
- Azure Monitor: The comprehensive monitoring solution for Azure. It collects, analyzes, and acts on telemetry from your cloud and on-premises environments.
- Application Insights: A feature of Azure Monitor that provides extensible application performance management (APM) and monitoring for live web applications.
- Log Analytics: A service within Azure Monitor for interactive querying of log data.
Using Application Insights for Deep Observability
Application Insights is automatically enabled for most Azure Functions when created in the Azure portal. It provides insights into:
- Requests: Track the number of requests, their success rate, and response times.
- Dependencies: Monitor calls your functions make to external services (databases, other APIs, etc.).
- Exceptions: Capture and analyze errors thrown by your functions.
- Performance: Identify performance bottlenecks and slow-running operations.
- Live Metrics: Get real-time performance data while your application is running.
Configuring Application Insights
If Application Insights is not enabled, you can add it to your Function App. The essential setting is the APPINSIGHTS_INSTRUMENTATIONKEY
or APPLICATIONINSIGHTS_CONNECTION_STRING
application setting.
APPLICATIONINSIGHTS_CONNECTION_STRING
for newer applications as it offers enhanced capabilities like live metrics.
Viewing Application Insights Data
Navigate to your Function App in the Azure portal, then select Application Insights from the left-hand menu.
The Application Map
The Application Map provides a visual representation of your application's components and their interactions, making it easy to spot failures or performance issues.
Performance and Failures
Drill down into Performance and Failures sections to analyze response times, request counts, and exception details.
Leveraging Azure Monitor and Log Analytics
Azure Monitor collects platform metrics and diagnostic logs for your Function App. Log Analytics allows you to query these logs using Kusto Query Language (KQL).
Platform Metrics
Monitor key metrics like:
Function Execution Count
Function Execution Units
Http 5xx
,Http 4xx
,Http 2xx
Memory Working Set
CPU Time
These metrics can be viewed in the Metrics blade of your Function App or as part of Azure Monitor dashboards.
Diagnostic Logs
Configure diagnostic settings to send logs to Log Analytics workspaces, Storage Accounts, or Event Hubs.
Common logs to enable:
FunctionAppLogs
: Application logs generated by your function code.HTTPRequests
: Logs for HTTP-triggered functions.AppServiceHTTPLogs
: Platform logs for the underlying App Service.
Querying Logs with KQL
Once logs are sent to a Log Analytics workspace, you can query them. Here are some example KQL queries:
// Get the last hour of function executions
traces
| where timestamp > ago(1h)
| order by timestamp desc
// Count function executions by function name in the last 24 hours
customEvents
| where name == "FunctionExecuted"
| summarize count() by tostring(customDimensions.FunctionName)
| order by count_ desc
// Find exceptions in the last 6 hours
exceptions
| where timestamp > ago(6h)
| project timestamp, problemId, outerMessage, details
Custom Telemetry and Logging
You can emit custom telemetry from your function code to gain deeper insights.
Logging within Function Code
Use the built-in logger provided by the Functions runtime:
// C# example
public static class MyFunction
{
[FunctionName("MyHttpTrigger")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
// ... your code ...
return new OkResult();
}
}
// JavaScript example
module.exports = async function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');
// ... your code ...
};
Sending Custom Events and Metrics
Using the Application Insights SDK, you can send custom events, metrics, and traces:
// C# example with Application Insights SDK
var telemetryClient = new TelemetryClient();
telemetryClient.TrackEvent("MyCustomEvent", new Dictionary<string, string> { {"Parameter", "Value"} });
telemetryClient.TrackMetric("ProcessingTime", durationInMilliseconds);
// JavaScript example with Application Insights SDK (Node.js)
const appInsights = require("applicationinsights");
appInsights.defaultClient.trackEvent({ name: "MyCustomEvent", properties: { "Parameter": "Value" } });
appInsights.defaultClient.trackMetric({ name: "ProcessingTime", value: durationInMilliseconds });
Alerting
Set up alerts in Azure Monitor based on metrics or log queries to be notified proactively of issues.
- Metric Alerts: Trigger alerts when a specific metric crosses a defined threshold (e.g., high HTTP 5xx errors).
- Log Alerts: Trigger alerts when a KQL query returns a certain number of results (e.g., a specific error message appears frequently).
Conclusion
By effectively utilizing Application Insights, Azure Monitor, and Log Analytics, you can gain comprehensive visibility into the health, performance, and operational status of your Azure Functions. Regularly reviewing these monitoring tools will help you maintain robust and reliable serverless applications.