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

      10 Top Node.js Development Companies for Enterprise-Scale Projects (2025-2026 Ranked & Reviewed)

      July 4, 2025

      12 Must-Know Cost Factors When Hiring Node.js Developers for Your Enterprise

      July 4, 2025

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

      July 3, 2025

      Avoid these common platform engineering mistakes

      July 3, 2025

      RIP, Perfect Dark — Xbox leadership canceled my most-anticipated game, and the developers deserved better

      July 6, 2025

      I keep seeing people at events taking notes on E-Ink tablets — so I tried one to see what all the fuss is about

      July 6, 2025

      “A fantastic device for creative users” — this $550 discount on ASUS’s 3K OLED creator laptop disappears before Prime Day

      July 5, 2025

      Distribution Release: Rhino Linux 2025.3

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

      Token System using PHP and MySQL

      July 6, 2025
      Recent

      Token System using PHP and MySQL

      July 6, 2025

      Create React UI component with uncontrollable

      July 6, 2025

      Flaget – new small 5kB CLI argument parser

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

      RIP, Perfect Dark — Xbox leadership canceled my most-anticipated game, and the developers deserved better

      July 6, 2025
      Recent

      RIP, Perfect Dark — Xbox leadership canceled my most-anticipated game, and the developers deserved better

      July 6, 2025

      I keep seeing people at events taking notes on E-Ink tablets — so I tried one to see what all the fuss is about

      July 6, 2025

      Le notizie minori del mondo GNU/Linux e dintorni della settimana nr 27/2025

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

    Artificial Intelligence

    Experiment with Gemini 2.0 Flash native image generation

    July 6, 2025
    Artificial Intelligence

    Introducing Gemma 3

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

    Microsoft turns on “reboot less” Hotpatch updates for Windows 11 Enterprise

    Operating Systems

    Chrome’s Split View gets close to Edge’s Split Screen with Tab Selection and Split Tabs toolbar button

    Operating Systems

    CVE-2025-37781 – HP Linux Kernel i2c cros-ec-tunnel NULL Pointer Dereference

    Common Vulnerabilities and Exposures (CVEs)

    BBC Uses AI to Resurrect Agatha Christie as Your Personal Writing Coach

    Artificial Intelligence

    Highlights

    Development

    How Agile Helps You Improve Your Agility

    May 12, 2025

    Objective The objective of this topic is to explore how the Agile methodology enhances an…

    Edward Snowden doesn’t use an iPhone for privacy reasons

    April 9, 2025

    ChromeOS M137 update boosts accessibility, sound, and IT management tools

    June 12, 2025

    Hackers Exploited 17-year-old Vulnerability to Weaponize Word Documents

    April 23, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

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