Sending Custom Logs from Azure Functions to Azure Monitor Logs
    • Dark
      Light
    • PDF

    Sending Custom Logs from Azure Functions to Azure Monitor Logs

    • Dark
      Light
    • PDF

    Article Summary

    #ServerlessTips - Azure Functions
    Author: Rahul Rai Microsoft MVP

    Azure Monitor Logs enable you to collect logs from applications deployed on any host such as Virtual Machines, Azure Functions, etc. and use queries to analyze collected data.

    In this article, we will learn the setup required to ship user-generated logs to Azure Monitor Logs and query them.

    Creating the Azure Function

    Use the following Azure CLI commands to create an Azure Function app. Remember to replace the resource names with the names you desire:

    az group create --name <resource group> --location eastus 
    az storage account create --name <storage account> --location eastus --resource-group <resource group> --sku "Standard_LRS"
    az functionapp create –name <function app> --storage-account <storage account> --consumption-plan-location "eastus" --resource-group <resource group> --functions-version 4 --os-type Windows
    

    Create an HTTP-triggered function in the app with the following settings:
    Picture125

    Replace the code generated by default for the function with the following code listing:

    using Microsoft.AspNetCore.Mvc;
    
    public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
    {
        log.LogInformation("Function visited at {DT}", DateTime.UtcNow.ToLongTimeString());
        return new OkObjectResult("Hello!");
    }
    

    Shipping Logs to Azure Monitor Logs

    In your function app, select Diagnostic settings and click on + Add diagnostic setting as follows:
    Picture223

    Configure the diagnostic setting to send the logs to the desired Log Analytics workspace as follows and click Save to save the settings:
    Picture319

    Use the Test/Run console to send a few requests to the function and generate logs from the executions.
    Picture417

    Visit your Log Analytics workspace and select Logs. Azure Functions write all logs to the FunctionAppLogs table. You can write the following query to filter the logs generated by your function:

    FunctionAppLogs
    | where FunctionName == "<Function Name>"
    | order by TimeGenerated desc
    

    The following screenshot shows the user-generated logs recorded in Azure Monitor Logs:
    Picture58

    Now that you have the log data available in Azure Monitor Logs, you can use it to analyze data, raise alerts, automatically export data, etc.

    MicrosoftTeams-image 491


    Was this article helpful?