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

      Sunshine And March Vibes (2025 Wallpapers Edition)

      May 20, 2025

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

      May 20, 2025

      How To Fix Largest Contentful Paint Issues With Subpart Analysis

      May 20, 2025

      How To Prevent WordPress SQL Injection Attacks

      May 20, 2025

      GPT-5 should have a higher “degree of scientific certainty” than the current ChatGPT — but with less model switching

      May 20, 2025

      Elon Musk’s Grok 3 AI coming to Azure proves Satya Nadella’s allegiance isn’t to OpenAI, but to maximizing Microsoft’s profit gains by heeding consumer demands

      May 20, 2025

      One of the most promising open-world RPGs in years is releasing next week on Xbox and PC

      May 20, 2025

      NVIDIA’s latest driver fixes some big issues with DOOM: The Dark Ages

      May 20, 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

      Community News: Latest PECL Releases (05.20.2025)

      May 20, 2025
      Recent

      Community News: Latest PECL Releases (05.20.2025)

      May 20, 2025

      Getting Started with Personalization in Sitecore XM Cloud: Enable, Extend, and Execute

      May 20, 2025

      Universal Design and Global Accessibility Awareness Day (GAAD)

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

      GPT-5 should have a higher “degree of scientific certainty” than the current ChatGPT — but with less model switching

      May 20, 2025
      Recent

      GPT-5 should have a higher “degree of scientific certainty” than the current ChatGPT — but with less model switching

      May 20, 2025

      Elon Musk’s Grok 3 AI coming to Azure proves Satya Nadella’s allegiance isn’t to OpenAI, but to maximizing Microsoft’s profit gains by heeding consumer demands

      May 20, 2025

      One of the most promising open-world RPGs in years is releasing next week on Xbox and PC

      May 20, 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

    Security

    Nmap 7.96 Launches with Lightning-Fast DNS and 612 Scripts

    May 20, 2025
    Common Vulnerabilities and Exposures (CVEs)

    CVE-2025-30193 – DNSdist TCP Stack Exhaustion Denial of Service Vulnerability

    May 20, 2025
    Leave A Reply Cancel Reply

    Continue Reading

    Unveiling the Future: Srinidhi Ranganathan’s Vision of India’s AI Tech-Style Theme Park Comes to Life

    Artificial Intelligence

    20+ Free Analog Film Lightroom Presets for Photographers

    Development

    First time buyer mortgage Leeds | Right to Buy Mortgage Advice Leeds

    Web Development

    OmniGlue: The First Learnable Image Matcher Designed with Generalization as a Core Principle

    Development

    Highlights

    Feb 21, 2025: Development tools that have recently added new AI capabilities

    February 22, 2025

    Software companies are constantly trying to add more and more AI features to their platforms,…

    Unlocking the Potential of SirLLM: Advancements in Memory Retention and Attention Mechanisms

    May 27, 2024

    The Xbox Game Pass account will cost you more Microsoft Rewards points

    February 25, 2025

    The gaming stories and trends that defined 2024

    December 27, 2024
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

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