Azure Functions

ServerlessMicrosoft Azure.NETPythonJavaScriptJava

Platform

Azure Functions

Overview

Azure Functions is Microsoft Azure's enterprise-grade serverless computing platform. As an event-driven, scalable execution environment, it supports diverse languages including .NET, Python, JavaScript, Java, Go, and Rust, with rich Azure service integrations that powerfully support enterprise application development. As of 2025, with the Flex Consumption Plan, significant cold start performance improvements, enhanced AI integration, new Kafka/Event Grid trigger support, and next-generation containerized deployment capabilities, it has evolved beyond traditional serverless computing constraints to become a comprehensive platform that supports large-scale enterprise workloads.

Details

Azure Functions 2025 edition provides a comprehensive application development platform that goes beyond mere serverless execution environments, leveraging Microsoft's rich enterprise experience and deep cloud service integration. Particularly noteworthy is the new Flex Consumption Plan, which enables scaling up to 1,000 instances, 4096MB memory support, and VNet integration for enterprise security compliance. With Project Teleport achieving 15x faster cold start improvements, Durable Functions for complex workflow management, complete integrated development experience with Visual Studio/VS Code/GitHub Actions, and AI capabilities through Azure OpenAI/Cognitive Services integration, it provides comprehensive solutions for modern application development.

Key Features

  • Multi-language Support: .NET, Python, JavaScript, Java, Go, Rust compatibility
  • Rich Triggers: HTTP, Timer, Blob, Queue, Service Bus, Kafka, Event Grid, and more
  • Azure Integration: Seamless integration with 200+ Azure services
  • Durable Functions: Stateful workflow execution environment
  • Enterprise Security: Managed Identity, VNet integration, Key Vault connectivity

Latest 2025 Features

  • Flex Consumption Plan: Up to 1,000 instances, 4GB memory, VNet integration
  • Cold Start Improvements: 15x faster with Project Teleport
  • New Language Support: Official Go and Rust language support
  • New Trigger Types: Kafka and Event Grid trigger additions
  • Enhanced AI Integration: Deep integration with Azure OpenAI and Cognitive Services

Advantages and Disadvantages

Advantages

  • Complete integration with Microsoft ecosystem for enhanced development efficiency
  • Rich language support and flexible development environment choices
  • Enterprise-grade security and compliance features
  • Complex workflow processing capabilities through Durable Functions
  • Excellent development and debugging experience with Visual Studio/VS Code
  • Full-stack development support through rich Azure service connectivity
  • Transparent pricing structure with generous free tier

Disadvantages

  • Azure ecosystem dependency and vendor lock-in
  • Potentially longer cold start times compared to other platforms
  • High learning curve due to complex configuration and numerous options
  • Limited compatibility with other cloud platforms
  • Resource limitations constraining large-scale processing
  • Barriers for Linux/macOS developers due to Windows-centric development culture

Reference Pages

Code Examples

Setup and Basic Configuration

# Install Azure Functions Core Tools
npm install -g azure-functions-core-tools@4 --unsafe-perm true

# Install Azure CLI (Windows)
winget install Microsoft.AzureCLI

# Install Azure CLI (macOS)
brew install azure-cli

# Install Azure CLI (Linux)
curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash

# Login to Azure account
az login

# Create new Function app project
func init MyFunctionApp --worker-runtime node
cd MyFunctionApp

# Create new function
func new --name HttpExample --template "HTTP trigger"

# Start local development server
func start

# Deploy to Azure (requires resource group and storage account)
az group create --name myResourceGroup --location eastus
az storage account create --name mystorageaccount --location eastus --resource-group myResourceGroup --sku Standard_LRS
az functionapp create --resource-group myResourceGroup --consumption-plan-location eastus --runtime node --runtime-version 18 --functions-version 4 --name MyFunctionApp --storage-account mystorageaccount

# Deploy application
func azure functionapp publish MyFunctionApp
// src/functions/httpExample.js - JavaScript HTTP Function
const { app } = require('@azure/functions');

app.http('httpExample', {
    methods: ['GET', 'POST'],
    authLevel: 'anonymous',
    handler: async (request, context) => {
        context.log('JavaScript HTTP trigger function processed a request.');
        
        // Get request data
        const name = request.query.get('name') || (await request.json())?.name || 'World';
        const method = request.method;
        const url = request.url;
        const headers = request.headers;
        
        // Create response
        const responseMessage = {
            message: `Hello, ${name}! This HTTP triggered function executed successfully.`,
            timestamp: new Date().toISOString(),
            method: method,
            url: url,
            userAgent: headers.get('user-agent'),
            correlationId: context.invocationId
        };
        
        return {
            status: 200,
            headers: {
                'Content-Type': 'application/json',
                'Access-Control-Allow-Origin': '*'
            },
            body: JSON.stringify(responseMessage, null, 2)
        };
    }
});

HTTP APIs and Routing

# function_app.py - Python HTTP Functions
import azure.functions as func
import logging
import json
from datetime import datetime

app = func.FunctionApp(http_auth_level=func.AuthLevel.FUNCTION)

@app.route(route="users", methods=["GET", "POST"])
def users_api(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')
    
    try:
        if req.method == "GET":
            # Handle GET request
            user_id = req.params.get('id')
            
            if user_id:
                # Return specific user information
                user = {
                    "id": user_id,
                    "name": f"User {user_id}",
                    "email": f"user{user_id}@example.com",
                    "created_at": datetime.utcnow().isoformat()
                }
                return func.HttpResponse(
                    json.dumps(user),
                    status_code=200,
                    mimetype="application/json"
                )
            else:
                # Return all users list
                users = [
                    {"id": i, "name": f"User {i}", "email": f"user{i}@example.com"}
                    for i in range(1, 6)
                ]
                return func.HttpResponse(
                    json.dumps({"users": users, "total": len(users)}),
                    status_code=200,
                    mimetype="application/json"
                )
        
        elif req.method == "POST":
            # Handle POST request
            try:
                req_body = req.get_json()
                
                # Create new user
                new_user = {
                    "id": 999,  # In actual implementation, generate appropriate ID
                    "name": req_body.get('name'),
                    "email": req_body.get('email'),
                    "created_at": datetime.utcnow().isoformat()
                }
                
                return func.HttpResponse(
                    json.dumps({
                        "message": "User created successfully",
                        "user": new_user
                    }),
                    status_code=201,
                    mimetype="application/json"
                )
                
            except ValueError:
                return func.HttpResponse(
                    json.dumps({"error": "Invalid JSON"}),
                    status_code=400,
                    mimetype="application/json"
                )
    
    except Exception as e:
        logging.error(f"Error processing request: {str(e)}")
        return func.HttpResponse(
            json.dumps({"error": "Internal server error"}),
            status_code=500,
            mimetype="application/json"
        )

@app.route(route="health")
def health_check(req: func.HttpRequest) -> func.HttpResponse:
    health_info = {
        "status": "healthy",
        "timestamp": datetime.utcnow().isoformat(),
        "version": "1.0.0",
        "environment": "production"
    }
    
    return func.HttpResponse(
        json.dumps(health_info),
        status_code=200,
        mimetype="application/json"
    )

Database Integration and Data Processing

// UserFunction.cs - C# Cosmos DB Integration
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Azure.Cosmos;
using Newtonsoft.Json;

public class User
{
    public string id { get; set; }
    public string name { get; set; }
    public string email { get; set; }
    public DateTime createdAt { get; set; }
}

public class UserFunction
{
    private readonly CosmosClient _cosmosClient;
    private readonly Container _container;

    public UserFunction(CosmosClient cosmosClient)
    {
        _cosmosClient = cosmosClient;
        _container = _cosmosClient.GetContainer("MyDatabase", "Users");
    }

    [FunctionName("CreateUser")]
    public async Task<IActionResult> CreateUser(
        [HttpTrigger(AuthorizationLevel.Function, "post", Route = "users")] HttpRequest req,
        ILogger log)
    {
        log.LogInformation("CreateUser function processed a request.");

        try
        {
            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);

            var user = new User
            {
                id = Guid.NewGuid().ToString(),
                name = data?.name,
                email = data?.email,
                createdAt = DateTime.UtcNow
            };

            // Save to Cosmos DB
            await _container.CreateItemAsync(user, new PartitionKey(user.id));

            return new OkObjectResult(new
            {
                message = "User created successfully",
                user = user
            });
        }
        catch (Exception ex)
        {
            log.LogError($"Error creating user: {ex.Message}");
            return new BadRequestObjectResult(new { error = "Failed to create user" });
        }
    }

    [FunctionName("GetUsers")]
    public async Task<IActionResult> GetUsers(
        [HttpTrigger(AuthorizationLevel.Function, "get", Route = "users")] HttpRequest req,
        ILogger log)
    {
        log.LogInformation("GetUsers function processed a request.");

        try
        {
            var queryDefinition = new QueryDefinition("SELECT * FROM c ORDER BY c.createdAt DESC");
            var query = _container.GetItemQueryIterator<User>(queryDefinition);

            var users = new List<User>();
            while (query.HasMoreResults)
            {
                var response = await query.ReadNextAsync();
                users.AddRange(response);
            }

            return new OkObjectResult(new
            {
                users = users,
                total = users.Count
            });
        }
        catch (Exception ex)
        {
            log.LogError($"Error getting users: {ex.Message}");
            return new BadRequestObjectResult(new { error = "Failed to get users" });
        }
    }

    [FunctionName("ProcessBlobStorage")]
    public async Task ProcessBlobStorage(
        [BlobTrigger("uploads/{name}", Connection = "AzureWebJobsStorage")] Stream myBlob,
        string name,
        ILogger log)
    {
        log.LogInformation($"C# Blob trigger function processed blob\n Name:{name} \n Size: {myBlob.Length} Bytes");

        try
        {
            // Process file content
            using var reader = new StreamReader(myBlob);
            var content = await reader.ReadToEndAsync();

            // Save file information to Cosmos DB
            var fileInfo = new
            {
                id = Guid.NewGuid().ToString(),
                fileName = name,
                size = myBlob.Length,
                contentPreview = content.Substring(0, Math.Min(content.Length, 100)),
                processedAt = DateTime.UtcNow
            };

            await _container.CreateItemAsync(fileInfo, new PartitionKey(fileInfo.id));

            log.LogInformation($"File {name} processed and logged to database.");
        }
        catch (Exception ex)
        {
            log.LogError($"Error processing blob {name}: {ex.Message}");
        }
    }
}

Authentication and Security

// AuthenticationFunction.cs - JWT Authentication System
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using System.Threading.Tasks;
using BCrypt.Net;

public class AuthenticationFunction
{
    private readonly string _jwtSecret = Environment.GetEnvironmentVariable("JWT_SECRET");
    private readonly int _jwtExpiryInDays = 7;

    [FunctionName("Login")]
    public async Task<IActionResult> Login(
        [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "auth/login")] HttpRequest req,
        ILogger log)
    {
        log.LogInformation("Login function processed a request.");

        try
        {
            var requestBody = await req.ReadAsStringAsync();
            dynamic data = Newtonsoft.Json.JsonConvert.DeserializeObject(requestBody);

            string email = data?.email;
            string password = data?.password;

            // User authentication (in actual implementation, retrieve from database)
            var user = await AuthenticateUser(email, password);
            if (user == null)
            {
                return new UnauthorizedObjectResult(new { error = "Invalid credentials" });
            }

            // Generate JWT token
            var token = GenerateJwtToken(user);

            return new OkObjectResult(new
            {
                token = token,
                user = new
                {
                    id = user.Id,
                    email = user.Email,
                    name = user.Name
                },
                expiresIn = TimeSpan.FromDays(_jwtExpiryInDays).TotalSeconds
            });
        }
        catch (Exception ex)
        {
            log.LogError($"Login error: {ex.Message}");
            return new BadRequestObjectResult(new { error = "Login failed" });
        }
    }

    [FunctionName("ValidateToken")]
    public IActionResult ValidateToken(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "auth/validate")] HttpRequest req,
        ILogger log)
    {
        try
        {
            var token = req.Headers["Authorization"].ToString().Replace("Bearer ", "");
            var principal = ValidateJwtToken(token);

            if (principal == null)
            {
                return new UnauthorizedObjectResult(new { error = "Invalid token" });
            }

            return new OkObjectResult(new
            {
                valid = true,
                user = new
                {
                    id = principal.FindFirst("sub")?.Value,
                    email = principal.FindFirst("email")?.Value,
                    name = principal.FindFirst("name")?.Value
                }
            });
        }
        catch (Exception ex)
        {
            log.LogError($"Token validation error: {ex.Message}");
            return new UnauthorizedObjectResult(new { error = "Invalid token" });
        }
    }

    private string GenerateJwtToken(User user)
    {
        var tokenHandler = new JwtSecurityTokenHandler();
        var key = Encoding.ASCII.GetBytes(_jwtSecret);
        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(new[]
            {
                new Claim("sub", user.Id),
                new Claim("email", user.Email),
                new Claim("name", user.Name)
            }),
            Expires = DateTime.UtcNow.AddDays(_jwtExpiryInDays),
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
        };
        var token = tokenHandler.CreateToken(tokenDescriptor);
        return tokenHandler.WriteToken(token);
    }

    private ClaimsPrincipal ValidateJwtToken(string token)
    {
        try
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.ASCII.GetBytes(_jwtSecret);
            tokenHandler.ValidateToken(token, new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(key),
                ValidateIssuer = false,
                ValidateAudience = false,
                ClockSkew = TimeSpan.Zero
            }, out SecurityToken validatedToken);

            var jwtToken = (JwtSecurityToken)validatedToken;
            return new ClaimsPrincipal(new ClaimsIdentity(jwtToken.Claims));
        }
        catch
        {
            return null;
        }
    }

    private async Task<User> AuthenticateUser(string email, string password)
    {
        // In actual implementation, retrieve user information from database
        // Sample data here
        var hashedPassword = BCrypt.Net.BCrypt.HashPassword("password123");
        
        if (email == "[email protected]" && BCrypt.Net.BCrypt.Verify(password, hashedPassword))
        {
            return new User
            {
                Id = "user123",
                Email = email,
                Name = "Test User"
            };
        }
        
        return null;
    }
}

Event-Driven Architecture

# durable_functions.py - Durable Functions Workflow
import azure.functions as func
import azure.durable_functions as df
import json
import logging
from datetime import datetime, timedelta

# Orchestrator Function - Controls entire workflow
@df.orchestrator_trigger(context_name="context")
def process_order_orchestrator(context: df.DurableOrchestrationContext):
    """
    Order processing workflow orchestrator
    """
    try:
        # Get input data
        order_data = context.get_input()
        order_id = order_data.get("orderId")
        
        logging.info(f"Starting order processing for order: {order_id}")
        
        # Step 1: Check inventory
        inventory_result = yield context.call_activity("check_inventory", order_data)
        if not inventory_result["available"]:
            return {"status": "failed", "reason": "insufficient_inventory"}
        
        # Step 2: Process payment
        payment_result = yield context.call_activity("process_payment", order_data)
        if not payment_result["success"]:
            # Restore inventory
            yield context.call_activity("restore_inventory", order_data)
            return {"status": "failed", "reason": "payment_failed"}
        
        # Step 3: Prepare shipping (parallel execution)
        shipping_tasks = [
            context.call_activity("prepare_shipping", order_data),
            context.call_activity("send_confirmation_email", order_data)
        ]
        results = yield context.task_all(shipping_tasks)
        
        # Step 4: Delayed shipping start (using timer)
        shipping_date = context.current_utc_datetime + timedelta(hours=2)
        yield context.create_timer(shipping_date)
        
        # Step 5: Start shipping
        shipping_result = yield context.call_activity("start_shipping", order_data)
        
        return {
            "status": "completed",
            "orderId": order_id,
            "shippingTrackingNumber": shipping_result["trackingNumber"],
            "completedAt": context.current_utc_datetime.isoformat()
        }
        
    except Exception as e:
        logging.error(f"Order processing failed: {str(e)}")
        return {"status": "error", "message": str(e)}

# Activity Functions - Individual task execution
@df.activity_trigger(input_name="order_data")
def check_inventory(order_data: dict) -> dict:
    """Check inventory"""
    logging.info(f"Checking inventory for order: {order_data['orderId']}")
    
    # In actual implementation, check inventory database
    items = order_data.get("items", [])
    for item in items:
        # Inventory check logic (sample)
        if item["quantity"] > 10:  # Temporary inventory limit
            return {"available": False, "item": item["productId"]}
    
    return {"available": True}

@df.activity_trigger(input_name="order_data")
def process_payment(order_data: dict) -> dict:
    """Process payment"""
    logging.info(f"Processing payment for order: {order_data['orderId']}")
    
    # In actual implementation, integrate with payment gateway
    payment_info = order_data.get("payment", {})
    amount = order_data.get("totalAmount", 0)
    
    # Sample payment processing
    if amount > 0 and payment_info.get("cardNumber"):
        return {
            "success": True,
            "transactionId": f"txn_{order_data['orderId']}_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}"
        }
    
    return {"success": False, "error": "Invalid payment information"}

@df.activity_trigger(input_name="order_data")
def send_confirmation_email(order_data: dict) -> dict:
    """Send confirmation email"""
    logging.info(f"Sending confirmation email for order: {order_data['orderId']}")
    
    # In actual implementation, use email service
    customer_email = order_data.get("customerEmail")
    
    # Use SendGrid or Azure Communication Services
    return {
        "sent": True,
        "email": customer_email,
        "sentAt": datetime.utcnow().isoformat()
    }

# HTTP Trigger - Start workflow
@app.route(route="orders", methods=["POST"])
@df.durable_client_input(client_name="client")
async def start_order_processing(req: func.HttpRequest, client: df.DurableOrchestrationClient) -> func.HttpResponse:
    try:
        req_body = req.get_json()
        order_id = req_body.get("orderId")
        
        # Start orchestration
        instance_id = await client.start_new("process_order_orchestrator", None, req_body)
        
        logging.info(f"Started orchestration with ID = {instance_id}")
        
        # Generate management URLs (for status checking)
        management_urls = client.create_check_status_response(req, instance_id)
        
        return func.HttpResponse(
            json.dumps({
                "instanceId": instance_id,
                "orderId": order_id,
                "status": "started",
                "statusQueryGetUri": management_urls.get_data()["statusQueryGetUri"]
            }),
            status_code=202,
            mimetype="application/json"
        )
        
    except Exception as e:
        logging.error(f"Error starting order processing: {str(e)}")
        return func.HttpResponse(
            json.dumps({"error": "Failed to start order processing"}),
            status_code=500,
            mimetype="application/json"
        )

# Event Grid Trigger - 2025 New Feature
@app.event_grid_trigger(arg_name="event")
def handle_event_grid(event: func.EventGridEvent):
    """Process Event Grid events"""
    logging.info(f"Received Event Grid event: {event.event_type}")
    
    try:
        event_data = event.get_json()
        
        if event.event_type == "Microsoft.Storage.BlobCreated":
            # Process blob creation event
            blob_url = event_data["url"]
            blob_name = event_data["subject"].split("/")[-1]
            
            logging.info(f"New blob created: {blob_name}")
            
            # File processing logic (e.g., image resize, text analysis, etc.)
            
        elif event.event_type == "Microsoft.EventGrid.SubscriptionValidationEvent":
            # Subscription validation
            validation_code = event_data["validationCode"]
            return {"validationResponse": validation_code}
            
    except Exception as e:
        logging.error(f"Error processing Event Grid event: {str(e)}")

Monitoring and Performance Optimization

// MonitoringFunction.cs - Custom Metrics and Monitoring
using System;
using System.Threading.Tasks;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using System.Diagnostics;
using System.Collections.Generic;

public class MonitoringFunction
{
    private readonly TelemetryClient _telemetryClient;

    public MonitoringFunction(TelemetryClient telemetryClient)
    {
        _telemetryClient = telemetryClient;
    }

    [FunctionName("PerformanceMonitoring")]
    public async Task<IActionResult> PerformanceMonitoring(
        [HttpTrigger(AuthorizationLevel.Function, "get", Route = "metrics")] HttpRequest req,
        ILogger log)
    {
        var stopwatch = Stopwatch.StartNew();
        
        try
        {
            // Collect custom metrics
            var metrics = new Dictionary<string, object>
            {
                ["timestamp"] = DateTime.UtcNow,
                ["environment"] = Environment.GetEnvironmentVariable("AZURE_FUNCTIONS_ENVIRONMENT") ?? "Development",
                ["functionApp"] = Environment.GetEnvironmentVariable("WEBSITE_SITE_NAME"),
                ["version"] = "1.0.0"
            };

            // Send custom event to Application Insights
            _telemetryClient.TrackEvent("HealthCheck", new Dictionary<string, string>
            {
                ["Status"] = "Healthy",
                ["Environment"] = metrics["environment"].ToString()
            });

            // Collect performance counters
            var performanceMetrics = new
            {
                memory_usage = GC.GetTotalMemory(false),
                active_requests = GetActiveRequestCount(),
                uptime_seconds = stopwatch.Elapsed.TotalSeconds
            };

            // Send custom metrics
            _telemetryClient.TrackMetric("MemoryUsage", performanceMetrics.memory_usage);
            _telemetryClient.TrackMetric("ActiveRequests", performanceMetrics.active_requests);

            stopwatch.Stop();

            return new OkObjectResult(new
            {
                status = "healthy",
                metrics = metrics,
                performance = performanceMetrics,
                execution_time_ms = stopwatch.ElapsedMilliseconds
            });
        }
        catch (Exception ex)
        {
            log.LogError($"Health check failed: {ex.Message}");
            
            // Send error metrics
            _telemetryClient.TrackException(ex, new Dictionary<string, string>
            {
                ["FunctionName"] = "PerformanceMonitoring",
                ["ErrorType"] = ex.GetType().Name
            });

            return new ObjectResult(new { status = "unhealthy", error = ex.Message })
            {
                StatusCode = 500
            };
        }
    }

    [FunctionName("CustomLogging")]
    public async Task<IActionResult> CustomLogging(
        [HttpTrigger(AuthorizationLevel.Function, "post", Route = "logs")] HttpRequest req,
        ILogger log)
    {
        try
        {
            var requestBody = await req.ReadAsStringAsync();
            dynamic data = Newtonsoft.Json.JsonConvert.DeserializeObject(requestBody);

            string level = data?.level ?? "Info";
            string message = data?.message ?? "No message";
            string source = data?.source ?? "Unknown";

            // Record structured logs
            using (log.BeginScope(new Dictionary<string, object>
            {
                ["Source"] = source,
                ["CorrelationId"] = Guid.NewGuid().ToString(),
                ["Timestamp"] = DateTime.UtcNow
            }))
            {
                switch (level.ToLower())
                {
                    case "error":
                        log.LogError("Custom Error: {Message}", message);
                        break;
                    case "warning":
                        log.LogWarning("Custom Warning: {Message}", message);
                        break;
                    case "info":
                    default:
                        log.LogInformation("Custom Info: {Message}", message);
                        break;
                }
            }

            // Send custom event to Application Insights
            _telemetryClient.TrackEvent("CustomLog", new Dictionary<string, string>
            {
                ["Level"] = level,
                ["Source"] = source,
                ["Message"] = message
            });

            return new OkObjectResult(new { status = "logged", level = level });
        }
        catch (Exception ex)
        {
            log.LogError($"Custom logging failed: {ex.Message}");
            return new BadRequestObjectResult(new { error = "Logging failed" });
        }
    }

    [FunctionName("AlertingSystem")]
    public async Task AlertingSystem(
        [TimerTrigger("0 */5 * * * *")] TimerInfo myTimer, // Execute every 5 minutes
        ILogger log)
    {
        log.LogInformation($"Alerting system check started at: {DateTime.Now}");

        try
        {
            // Check system health
            var healthChecks = await PerformHealthChecks();
            
            foreach (var check in healthChecks)
            {
                if (!check.IsHealthy)
                {
                    // Send alert
                    await SendAlert(check, log);
                    
                    // Send alert event to Application Insights
                    _telemetryClient.TrackEvent("HealthCheckAlert", new Dictionary<string, string>
                    {
                        ["CheckName"] = check.Name,
                        ["Status"] = "Unhealthy",
                        ["Details"] = check.Details
                    });
                }
            }
        }
        catch (Exception ex)
        {
            log.LogError($"Alerting system error: {ex.Message}");
        }
    }

    private async Task<List<HealthCheckResult>> PerformHealthChecks()
    {
        var results = new List<HealthCheckResult>();

        // Database connection check
        results.Add(await CheckDatabaseConnection());
        
        // External API connection check
        results.Add(await CheckExternalAPIConnection());
        
        // Storage account connection check
        results.Add(await CheckStorageConnection());

        return results;
    }

    private async Task<HealthCheckResult> CheckDatabaseConnection()
    {
        try
        {
            // Database connection test (e.g., Cosmos DB)
            // In actual implementation, use appropriate database client
            await Task.Delay(100); // Simulation
            
            return new HealthCheckResult
            {
                Name = "Database",
                IsHealthy = true,
                Details = "Connection successful"
            };
        }
        catch (Exception ex)
        {
            return new HealthCheckResult
            {
                Name = "Database",
                IsHealthy = false,
                Details = ex.Message
            };
        }
    }

    private async Task<HealthCheckResult> CheckExternalAPIConnection()
    {
        try
        {
            // External API connection test
            using var httpClient = new System.Net.Http.HttpClient();
            httpClient.Timeout = TimeSpan.FromSeconds(10);
            
            var response = await httpClient.GetAsync("https://api.example.com/health");
            
            return new HealthCheckResult
            {
                Name = "ExternalAPI",
                IsHealthy = response.IsSuccessStatusCode,
                Details = $"Status: {response.StatusCode}"
            };
        }
        catch (Exception ex)
        {
            return new HealthCheckResult
            {
                Name = "ExternalAPI",
                IsHealthy = false,
                Details = ex.Message
            };
        }
    }

    private async Task<HealthCheckResult> CheckStorageConnection()
    {
        try
        {
            // Azure Storage connection test
            await Task.Delay(50); // Simulation
            
            return new HealthCheckResult
            {
                Name = "Storage",
                IsHealthy = true,
                Details = "Connection successful"
            };
        }
        catch (Exception ex)
        {
            return new HealthCheckResult
            {
                Name = "Storage",
                IsHealthy = false,
                Details = ex.Message
            };
        }
    }

    private async Task SendAlert(HealthCheckResult check, ILogger log)
    {
        // Send alert (e.g., Logic Apps, email, Slack, etc.)
        log.LogWarning($"ALERT: {check.Name} health check failed - {check.Details}");
        
        // In actual implementation, implement appropriate alert sending functionality
        await Task.CompletedTask;
    }

    private int GetActiveRequestCount()
    {
        // In actual implementation, use appropriate performance counters
        return new Random().Next(1, 10); // Sample value
    }
}

public class HealthCheckResult
{
    public string Name { get; set; }
    public bool IsHealthy { get; set; }
    public string Details { get; set; }
}