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

      Mirantis reveals Lens Prism, an AI copilot for operating Kubernetes clusters

      July 3, 2025

      Avoid these common platform engineering mistakes

      July 3, 2025

      Full-Stack Techies vs Toptal: Which Is Better for React.js Outsourcing?

      July 3, 2025

      The AI productivity paradox in software engineering: Balancing efficiency and human skill retention

      July 2, 2025

      Microsoft Gaming studios head Matt Booty says “overall portfolio strategy is unchanged” — with more than 40 games in production

      July 3, 2025

      Capcom reports that its Steam game sales have risen massively — despite flagship titles like Monster Hunter Wilds receiving profuse backlash from PC players

      July 3, 2025

      Cloudflare is fighting to safeguard “the future of the web itself” — standing directly in the way of leading AI firms

      July 3, 2025

      Microsoft reportedly lacks the know-how to fully leverage OpenAI’s tech — despite holding IP rights

      July 3, 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

      PHP 8.5.0 Alpha 1 available for testing

      July 3, 2025
      Recent

      PHP 8.5.0 Alpha 1 available for testing

      July 3, 2025

      Recording cross browser compatible media

      July 3, 2025

      Celebrating Perficient’s Third Databricks Champion

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

      Microsoft Gaming studios head Matt Booty says “overall portfolio strategy is unchanged” — with more than 40 games in production

      July 3, 2025
      Recent

      Microsoft Gaming studios head Matt Booty says “overall portfolio strategy is unchanged” — with more than 40 games in production

      July 3, 2025

      Capcom reports that its Steam game sales have risen massively — despite flagship titles like Monster Hunter Wilds receiving profuse backlash from PC players

      July 3, 2025

      Cloudflare is fighting to safeguard “the future of the web itself” — standing directly in the way of leading AI firms

      July 3, 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

    Development

    Don’t Choose the Wrong Web Team — Here’s Why It Matters

    July 3, 2025
    Artificial Intelligence

    Introducing Gemma 3

    July 3, 2025
    Leave A Reply Cancel Reply

    For security, use of Google's reCAPTCHA service is required which is subject to the Google Privacy Policy and Terms of Use.

    Continue Reading

    Extend your Amazon Q Business with PagerDuty Advance data accessor

    Machine Learning

    CVE-2025-46380 – Apache HTTP Server Unvalidated User Input

    Common Vulnerabilities and Exposures (CVEs)

    Google’s New AI Tries Talking Dolphin – and It’s Getting Pretty Good at It

    Operating Systems

    CVE-2025-5584 – PHPGurukul Hospital Management System Cross Site Scripting Vulnerability

    Common Vulnerabilities and Exposures (CVEs)

    Highlights

    Machine Learning

    Researchers from Dataocean AI and Tsinghua University Introduces Dolphin: A Multilingual Automatic Speech Recognition ASR Model Optimized for Eastern Languages and Dialects

    April 3, 2025

    Automatic speech recognition (ASR) technologies have advanced significantly, yet notable disparities remain in their ability…

    CVE-2025-4348 – D-Link DIR-600L L2TP Buffer Overflow

    May 6, 2025

    AI Adoption in the Enterprise: Breaking Through the Security and Compliance Gridlock

    April 3, 2025

    CVE-2025-5093 – WordPress Responsive Lightbox & Gallery Stored Cross-Site Scripting Vulnerability

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

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