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

      CodeSOD: A Unique Way to Primary Key

      July 22, 2025

      BrowserStack launches Figma plugin for detecting accessibility issues in design phase

      July 22, 2025

      Parasoft brings agentic AI to service virtualization in latest release

      July 22, 2025

      Node.js vs. Python for Backend: 7 Reasons C-Level Leaders Choose Node.js Talent

      July 21, 2025

      The best CRM software with email marketing in 2025: Expert tested and reviewed

      July 22, 2025

      This multi-port car charger can power 4 gadgets at once – and it’s surprisingly cheap

      July 22, 2025

      I’m a wearables editor and here are the 7 Pixel Watch 4 rumors I’m most curious about

      July 22, 2025

      8 ways I quickly leveled up my Linux skills – and you can too

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

      The Intersection of Agile and Accessibility – A Series on Designing for Everyone

      July 22, 2025
      Recent

      The Intersection of Agile and Accessibility – A Series on Designing for Everyone

      July 22, 2025

      Zero Trust & Cybersecurity Mesh: Your Org’s Survival Guide

      July 22, 2025

      Execute Ping Commands and Get Back Structured Data in PHP

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

      A Tomb Raider composer has been jailed — His legacy overshadowed by $75k+ in loan fraud

      July 22, 2025
      Recent

      A Tomb Raider composer has been jailed — His legacy overshadowed by $75k+ in loan fraud

      July 22, 2025

      “I don’t think I changed his mind” — NVIDIA CEO comments on H20 AI GPU sales resuming in China following a meeting with President Trump

      July 22, 2025

      Galaxy Z Fold 7 review: Six years later — Samsung finally cracks the foldable code

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

    GPT-5 is Coming: Revolutionizing Software Testing

    July 22, 2025
    Development

    Win the Accessibility Game: Combining AI with Human Judgment

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

    CVE-2025-7343 – Digiwin SFT SQL Injection

    Common Vulnerabilities and Exposures (CVEs)

    CVE-2025-32730 – i-PRO Co., Ltd. Surveillance Cameras and Recorders Cryptographic Key Hard-Coded Authentication Bypass

    Common Vulnerabilities and Exposures (CVEs)

    Modernize and migrate on-premises fraud detection machine learning workflows to Amazon SageMaker

    Machine Learning

    CVE-2025-7213 – FNKvision FNK-GU2 UART Interface Debug Interface Access Control Vulnerability

    Common Vulnerabilities and Exposures (CVEs)

    Highlights

    CVE-2025-6543 – Citrix NetScaler ADC and Gateway Unauthenticated Remote Code Execution and Denial of Service Vulnerability

    June 25, 2025

    CVE ID : CVE-2025-6543

    Published : June 25, 2025, 1:15 p.m. | 40 minutes ago

    Description : Memory overflow vulnerability leading to unintended control flow and Denial of Service in NetScaler ADC and NetScaler Gateway when configured as Gateway (VPN virtual server, ICA Proxy, CVPN, RDP Proxy) OR AAA virtual server

    Severity: 0.0 | NA

    Visit the link for more details, such as CVSS details, affected products, timeline, and more…

    CVE-2025-5905 – TOTOLINK T10 Buffer Overflow in POST Request Handler

    June 9, 2025

    CVE-2025-52441 – Apache HTTP Server Cross-Site Request Forgery

    June 17, 2025

    Convert Any Value to Collections with Laravel’s Collection::wrap Method

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

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