Azure Functions Monitoring and Logging
When a function runs in the cloud, there is no terminal window to watch. Monitoring and logging tell developers what the function is doing, whether it succeeded, how long it took, and what went wrong when it fails. Application Insights is the Azure service that collects, stores, and displays all of this information.
What Is Application Insights?
Application Insights is an Azure monitoring service that automatically collects telemetry from Azure Functions. Telemetry includes logs, exceptions, request duration, failure rates, and dependency calls (calls to databases, external APIs, queues).
┌──────────────────────────────────────────────────────────────┐ │ APPLICATION INSIGHTS DATA FLOW │ │ │ │ Azure Function runs │ │ │ │ │ │ Emits telemetry automatically: │ │ │ • Request start and end time │ │ │ • context.log() messages │ │ │ • Any exceptions that occur │ │ │ • Calls to external services (duration + status) │ │ │ │ │ ▼ │ │ Application Insights collects data │ │ │ │ │ ▼ │ │ Azure Portal → Live Metrics, Logs, Failures, Performance │ └──────────────────────────────────────────────────────────────┘
Connecting Application Insights to a Function App
When creating a Function App in Azure Portal, Application Insights is offered as an optional connection. It is strongly recommended to enable it. After enabling, Application Insights automatically receives telemetry without any code changes.
The connection between the Function App and Application Insights uses a setting called APPLICATIONINSIGHTS_CONNECTION_STRING in App Settings.
# Add Application Insights connection string via CLI az functionapp config appsettings set \ --name MyFunctionApp \ --resource-group MyResourceGroup \ --settings "APPLICATIONINSIGHTS_CONNECTION_STRING=InstrumentationKey=abc123..."
Logging in Function Code
The context.log object provides multiple log severity levels. Each level shows up in Application Insights with the corresponding severity.
module.exports = async function (context, req) {
// Basic informational log
context.log("Function started processing request");
// Verbose (detailed debug info)
context.log.verbose("Detailed debug: request body size =", JSON.stringify(req.body).length);
// Warning — something unexpected but recoverable
context.log.warn("Request is missing optional field: 'phone'");
// Error — something failed
context.log.error("Failed to connect to payment gateway");
try {
const result = await processOrder(req.body);
context.log("Order processed successfully. Order ID:", result.orderId);
context.res = { status: 200, body: result };
} catch (err) {
// Log the full error with stack trace
context.log.error("Unexpected error:", err.message);
context.log.error("Stack:", err.stack);
context.res = { status: 500, body: "Internal server error" };
}
};
Log Levels
| Method | Severity | When to Use |
|---|---|---|
| context.log.verbose() | Verbose | Highly detailed debug info (usually disabled in production) |
| context.log() | Information | Normal flow messages — function started, order saved, email sent |
| context.log.warn() | Warning | Unexpected but non-breaking situations |
| context.log.error() | Error | Failures that need attention — exceptions, API failures |
Configuring Log Level in host.json
The minimum log level controls which messages get recorded. Setting it too low (Verbose) generates too much data and increases cost. Setting it too high (Error) misses useful information.
{
"version": "2.0",
"logging": {
"applicationInsights": {
"samplingSettings": {
"isEnabled": true,
"maxTelemetryItemsPerSecond": 20
}
},
"logLevel": {
"default": "Information",
"Host.Results": "Error",
"Function": "Information",
"Host.Aggregator": "Trace"
}
}
}
| Log Level | Records Messages At |
|---|---|
| Trace / Verbose | Everything (most verbose) |
| Debug | Debug and above |
| Information | Information, Warning, Error, Critical |
| Warning | Warning, Error, Critical |
| Error | Error and Critical only |
| None | Nothing (disable logging completely) |
Application Insights in Azure Portal
Key Sections to Know
| Section | What It Shows | Common Use |
|---|---|---|
| Live Metrics | Real-time activity as the function runs | Watch requests arriving in real time |
| Failures | Exceptions, failed requests, dependency failures | Find and investigate errors |
| Performance | Request duration, slowest operations | Identify bottlenecks |
| Logs (Kusto) | Raw telemetry queryable with Kusto Query Language | Search logs, build custom reports |
| Application Map | Visual diagram of function and its dependencies | Understand what the function calls |
| Alerts | Rules that trigger notifications on conditions | Get email when failure rate exceeds 5% |
Querying Logs with Kusto Query Language (KQL)
Logs in Application Insights are stored in structured tables and can be queried using Kusto Query Language (KQL). KQL is similar to SQL but optimized for log data.
Example 1 – View Recent Function Executions
requests | where timestamp > ago(1h) | order by timestamp desc | project timestamp, name, success, duration, resultCode
Example 2 – Find All Errors in the Last 24 Hours
exceptions | where timestamp > ago(24h) | project timestamp, type, message = outerMessage, details = details[0].message | order by timestamp desc
Example 3 – Average Function Duration by Name
requests | where timestamp > ago(7d) | summarize avgDuration = avg(duration), callCount = count() by name | order by avgDuration desc
Example 4 – Count Errors per Hour
exceptions | where timestamp > ago(24h) | summarize errorCount = count() by bin(timestamp, 1h) | order by timestamp asc
Setting Up Alerts
Alerts automatically notify when something goes wrong, without anyone having to watch the dashboard all day.
┌──────────────────────────────────────────────────────────────┐ │ ALERT SETUP EXAMPLE │ │ │ │ Condition: Failure rate > 5% in the last 5 minutes │ │ │ │ │ ▼ │ │ Alert fires │ │ │ │ │ ▼ │ │ Action Group runs: │ │ • Send email to dev-team@company.com │ │ • Send SMS to on-call engineer │ │ • Post message to Microsoft Teams channel │ └──────────────────────────────────────────────────────────────┘
Set up alerts in Azure Portal → Application Insights → Alerts → New Alert Rule.
Custom Telemetry – Tracking Business Events
Beyond automatic logs, custom events track meaningful business activities — like a successful checkout, a failed login attempt, or a large order placed.
const appInsights = require("applicationinsights");
module.exports = async function (context, req) {
const order = req.body;
// Track a custom business event
appInsights.defaultClient.trackEvent({
name: "OrderPlaced",
properties: {
orderId: order.id,
orderValue: order.total.toString(),
city: order.city
}
});
// Track a custom metric
appInsights.defaultClient.trackMetric({
name: "OrderValue",
value: order.total
});
context.res = { status: 201, body: { success: true } };
};
Custom events appear in the Application Insights customEvents table and can be visualized as charts in dashboards.
