Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      Sunshine And March Vibes (2025 Wallpapers Edition)

      May 9, 2025

      The Case For Minimal WordPress Setups: A Contrarian View On Theme Frameworks

      May 9, 2025

      How To Fix Largest Contentful Paint Issues With Subpart Analysis

      May 9, 2025

      How To Prevent WordPress SQL Injection Attacks

      May 9, 2025

      This Motorola Razr deal at Best Buy is the top offer I’ve seen on the flip phone

      May 9, 2025

      Google Maps can identify and save places in your screenshots – here’s how

      May 9, 2025

      T-Mobile is giving loyal users a free line right now – how to see if you qualify

      May 9, 2025

      CTA warns of tariff-fueled price hikes on consumer tech – but it’s not all bad news

      May 9, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      Big Node, VS Code, and Mantine updates

      May 9, 2025
      Recent

      Big Node, VS Code, and Mantine updates

      May 9, 2025

      Prepare for Contact Center Week with Colleen Eager

      May 9, 2025

      Preparing for the Unthinkable: Safeguarding People and Productivity During India-Pakistan Conflicts

      May 9, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      Microsoft confirms Offline Calendar for New Outlook on Windows 11

      May 9, 2025
      Recent

      Microsoft confirms Offline Calendar for New Outlook on Windows 11

      May 9, 2025

      Windows 11 Microsoft Store tests Copilot integration to increase app downloads

      May 9, 2025

      Beyond APT: Software Management with Flatpak on Ubuntu

      May 9, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»Log Framework Integration in Azure Functions with Azure Cosmos DB

    Log Framework Integration in Azure Functions with Azure Cosmos DB

    April 2, 2025

    Introduction

    Logging is an essential part of application development, especially in cloud environments where monitoring and debugging are crucial. In Azure Functions, there is no built-in provision to log application-level details into a centralized database, making it challenging to check logs every time in the Azure portal. This blog focuses on integrating NLog into Azure Functions to store all logs in a single database (Cosmos DB), ensuring a unified logging approach for better monitoring and debugging.

    Steps to Integrate Logging Framework

    Integration steps

     

    1. Create an Azure Function Project

    Begin by creating an Azure Function project using the Azure Function template in Visual Studio.

    2. Install Required Nuget Packages

    To enable logging using NLog, install the following NuGet packages:Function App Explorer

    Install-Package NLog
    Install-Package NLog.Extensions.Logging
    Install-Package Microsoft.Azure.Cosmos

     

     

    3. Create and Configure Nlog.config

    NLog uses an XML-based configuration file to define logging targets and rules. Create a new file named Nlog.config in the project root and configure it with the necessary settings.

    Refer to the official NLog documentation for database target configuration: NLog Database Target

    Important: Set Copy to Output Directory to Copy Always in the file properties to ensure deployment.

    N Log Config Code

     

    4. Create Log Database

    Create an Azure Cosmos DB account with the SQL API.

    Sample Cosmos DB Database and Container

    1. Database Name: LogDemoDb
    2. Container Name: Logs
    3. Partition Key: /Application

    5. Define Necessary Variables

    In the local.settings.json file, define the Cosmos DB connection string.

    {
      "IsEncrypted": false,
      "Values": {
        "AzureWebJobsStorage": "UseDevelopmentStorage=true",
        "CosmosDBConnectionString": "AccountEndpoint=https://your-cosmosdb.documents.azure.com:443/;AccountKey=your-account-key;"
      }
    }
    

    Json App Settings

     

    6. Configure NLog in Startup.cs

    Modify Startup.cs to configure NLog and instantiate database connection strings and log variables.

    using Microsoft.Azure.Functions.Extensions.DependencyInjection;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Logging;
    using NLog.Extensions.Logging;
    using Microsoft.Azure.Cosmos;
    
    [assembly: FunctionsStartup(typeof(MyFunctionApp.Startup))]
    namespace MyFunctionApp
    {
        public class Startup : FunctionsStartup
        {
            public override void Configure(IFunctionsHostBuilder builder)
            {
                builder.Services.AddLogging(loggingBuilder =>
                {
                    loggingBuilder.ClearProviders();
                    loggingBuilder.SetMinimumLevel(LogLevel.Information);
                    loggingBuilder.AddNLog();
                });
    
                builder.Services.AddSingleton(new CosmosClient(
                    Environment.GetEnvironmentVariable("CosmosDBConnectionString")));
            }
        }
    }
    

    Startup Code

     

    7. Add Logs in Necessary Places

    To ensure efficient logging, add logs based on the following log level hierarchy:

    Log Levels

    Example Logging in Function Code:

     

    using System;
    using System.Threading.Tasks;
    using Microsoft.Azure.Cosmos;
    using Microsoft.Azure.WebJobs;
    using Microsoft.Extensions.Logging;
    
    public class MyFunction
    {
        private readonly ILogger<MyFunction> _logger;
        private readonly CosmosClient _cosmosClient;
        private readonly Container _container;
    
        public MyFunction(ILogger<MyFunction> logger, CosmosClient cosmosClient)
        {
            _logger = logger;
            _cosmosClient = cosmosClient;
    
            // Initialize Cosmos DB container
            _container = _cosmosClient.GetContainer("YourDatabaseName", "YourContainerName");
        }
    
        [FunctionName("MyFunction")]
        public async Task Run([TimerTrigger("0 */5 * * * *")] TimerInfo myTimer)
        {
            var logEntry = new
            {
                id = Guid.NewGuid().ToString(),
                timestamp = DateTime.UtcNow,
                logLevel = "Information",
                message = "Function executed at " + DateTime.UtcNow
            };
    
            // Insert log into Cosmos DB
            await _container.CreateItemAsync(logEntry, new PartitionKey(logEntry.id));
    
            _logger.LogInformation("Function executed at {time}", DateTime.UtcNow);
        }
    }
    

    8. Deployment

    Once the function is ready, deploy it to Azure Function App using Visual Studio or Azure DevOps.

    Deployment Considerations:

    • Define necessary environment variables in Azure Function Configuration Settings.
    • Ensure Azure Function App Service and SQL Database are in the same network to avoid connection issues.
    • Monitor logs using Application Insights for additional diagnostics.

    Conclusion

    By following these steps, you can successfully integrate NLog into your Azure Functions for efficient logging. This setup enables real-time monitoring, structured log storage, and improved debugging capabilities.

    Source: Read More 

    Facebook Twitter Reddit Email Copy Link
    Previous ArticleDeena Piquion from Xerox on Data, Disruption, and Digital Natives
    Next Article Synthwave Mountains Scroll Animation Header Using Trig.js

    Related Posts

    Common Vulnerabilities and Exposures (CVEs)

    CVE-2025-3876 – WooCommerce WordPress Privilege Escalation Vulnerability

    May 10, 2025
    Common Vulnerabilities and Exposures (CVEs)

    CVE-2025-3878 – WooCommerce Stored Cross-Site Scripting Vulnerability

    May 10, 2025
    Leave A Reply Cancel Reply

    Continue Reading

    BayMark Health Services Reports Data Breach, Exposing Patient Information

    Development

    Corse GSM Data Breach: 200,000 Customer Details of French Telecom Giant Allegedly Compromised

    Development

    Authorities Ramp Up Efforts to Capture the Mastermind Behind Emotet

    Development

    WhatsApp Launches Private Processing to Enable AI Features While Protecting Message Privacy

    Development

    Highlights

    DistroWatch Weekly, Issue 1077

    June 30, 2024

    The DistroWatch news feed is brought to you by TUXEDO COMPUTERS. This week in DistroWatch Weekly:
    Review: The Unity desktop and Lomiri on Ubuntu Unity 24.04
    News: Ubuntu plans to run Wayland on NVIDIA cards, openSUSE updates Leap Micro, Debian releases refreshed media, UBports gaining contact synchronization, FreeDOS celebrates its 30th anniversary
    Questions and answers: Different distributions for different tasks
    Released….

    Cybercriminals Exploiting Microsoft’s Quick Assist Feature in Ransomware Attacks

    May 16, 2024

    Innodata’s Comprehensive Benchmarking of Llama2, Mistral, Gemma, and GPT for Factuality, Toxicity, Bias, and Hallucination Propensity

    July 9, 2024

    Rilasciato PeerTube 7.1: Miglioramenti per i Podcast e una Riproduzione più Stabile

    March 19, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.