How to Properly Pull NLog DB ConnectionString from appsettings.json
11:58 21 Jun 2021

I have my nlog.config file setup with a database target and want to read connectionstring from appsettings.json (and for anyone interested, the value in appsettings is actually stored in Azure KeyVault). What is the proper way to do this? I have ASP.NET core 3.1 application.

nlog.config






  
    
    
  
  
    
    
    
    
    
    
        
            
        
        
        
    

    
    

        
        
        
    

Relevant part of appsettings.json file:

{
  "NLogConfiguration": {
    "ConnectionString": "..."
  }
}

I have a breakpoint in my code to inspect the database target but the connectionString value doesn't get set. it is staying as ${configsetting:item=NLogConfiguration.ConnectionString}

I don't have any NLog code at startup. I have a wrapper class around NLog and am initializing it that way. That class is shown below:

DBLogManager

using System;
using System.Configuration;
using System.Globalization;
using System.Web;
using NLog;
using System.Xml;
using System.IO;
using System.Reflection;
using System.Text;
using Microsoft.Extensions.Configuration;

namespace DBLog.DBLogManager
{

    public class DBLogManager : IDBLogManager
    {
        static ILogger InitializeDBLogManager()
        {
            XmlDocument nLogConfig = new XmlDocument();
            var path = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "nlog.config");

            NLog.LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration(path);
            
            return LogManager.GetLogger("AppLogger");

        }
        private static readonly ILogger Logger = InitializeDBLogManager();
    }
}
c# nlog asp.net-core-3.1