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

MethodSeverityWhen to Use
context.log.verbose()VerboseHighly detailed debug info (usually disabled in production)
context.log()InformationNormal flow messages — function started, order saved, email sent
context.log.warn()WarningUnexpected but non-breaking situations
context.log.error()ErrorFailures 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 LevelRecords Messages At
Trace / VerboseEverything (most verbose)
DebugDebug and above
InformationInformation, Warning, Error, Critical
WarningWarning, Error, Critical
ErrorError and Critical only
NoneNothing (disable logging completely)

Application Insights in Azure Portal

Key Sections to Know

SectionWhat It ShowsCommon Use
Live MetricsReal-time activity as the function runsWatch requests arriving in real time
FailuresExceptions, failed requests, dependency failuresFind and investigate errors
PerformanceRequest duration, slowest operationsIdentify bottlenecks
Logs (Kusto)Raw telemetry queryable with Kusto Query LanguageSearch logs, build custom reports
Application MapVisual diagram of function and its dependenciesUnderstand what the function calls
AlertsRules that trigger notifications on conditionsGet 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.

Leave a Comment