Setting the NLog database connection string in the ASP.NET Core appsettings.json

This article shows how the NLog connection string for the DatabaseTarget can be configured in the appsettings.json in an ASP.NET Core project and not the XML nlog.config file. All the NLog target properties can be configured in code if required and not just in the NLog XML configuration file.


2020-01-12 Updated to .NET Core 3.1, NLog.Web.AspNetCore 4.9.0
2018-04-04 Updated to NLog.Web.AspNetCore 4.5.1, ASP.NET Core 2.0
2017.02.08 Updated to NLog.Web.AspNetCore 4.3.0 and VS2017 RC3
17.12.2016 Updated to ASP.NET Core 1.1

NLog posts in this series:

  1. ASP.NET Core logging with NLog and Microsoft SQL Server
  2. ASP.NET Core logging with NLog and Elasticsearch
  3. Settings the NLog database connection string in the ASP.NET Core appsettings.json
  4. .NET Core logging to MySQL using NLog
  5. .NET Core logging with NLog and PostgreSQL

The XML nlog.config file is the same as in the previous post, with no database connection string configured.

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns=""


    <target name="database" xsi:type="Database" >

<!-- THIS is not required, read from the appsettings.json


    The appsetting layouts require the NLog.Extended assembly.
    The aspnet-* layouts require the NLog.Web assembly.
    The Application value is determined by an AppName appSetting in Web.config.
    The "NLogDb" connection string determines the database that NLog write to.
    The create dbo.Log script in the comment below must be manually executed.

  Script for creating the dbo.Log table.

  CREATE TABLE [dbo].[Log] (
      [Id] [int] IDENTITY(1,1) NOT NULL,
      [Application] [nvarchar](50) NOT NULL,
      [Logged] [datetime] NOT NULL,
      [Level] [nvarchar](50) NOT NULL,
      [Message] [nvarchar](max) NOT NULL,
      [Logger] [nvarchar](250) NULL,
      [Callsite] [nvarchar](max) NULL,
      [Exception] [nvarchar](max) NULL,

              insert into dbo.Log (
              Application, Logged, Level, Message,
              Logger, CallSite, Exception
              ) values (
              @Application, @Logged, @Level, @Message,
              @Logger, @Callsite, @Exception

          <parameter name="@application" layout="AspNetCoreNlog" />
          <parameter name="@logged" layout="${date}" />
          <parameter name="@level" layout="${level}" />
          <parameter name="@message" layout="${message}" />

          <parameter name="@logger" layout="${logger}" />
          <parameter name="@callSite" layout="${callsite:filename=true}" />
          <parameter name="@exception" layout="${exception:tostring}" />

    <logger name="*" minlevel="Trace" writeTo="database" />

The NLog DatabaseTarget connectionstring is configured in the appsettings.json as described in the ASP.NET Core configuration docs.

    "Logging": {
        "IncludeScopes": false,
        "LogLevel": {
            "Default": "Debug",
            "System": "Information",
            "Microsoft": "Information"
    "ElasticsearchUrl": "http://localhost:9200",
    "ConnectionStrings": {
        "NLogDb": "Data Source=N275\\MSSQLSERVER2014;Initial Catalog=Nlogs;Integrated Security=True;"

The configuration is then read in the Startup constructor.

public Startup(IConfiguration configuration)
	Configuration = configuration;

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
	services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
	// Add framework services.


The Nlog DatabaseTagert is then configured to use the connection string from the app settings and sets all the DatabaseTarget instances for NLog to use this. All target properties can be configured in this way if required.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
	GlobalDiagnosticsContext.Set("configDir", "C:\\git\\damienbod\\AspNetCoreNlog\\Logs");
	GlobalDiagnosticsContext.Set("connectionString", Configuration.GetConnectionString("DefaultConnection"));

	if (env.IsDevelopment())



	app.UseEndpoints(endpoints =>
			name: "default",
			pattern: "{controller=Home}/{action=Index}/{id?}");



  1. Ristogod · · Reply

    I tried this in my application and simply could not get it to work. If you put the connection string directly in the nlog.config database target, it works fine. But if I try and set it using the above code, it fails every time.

    Error when writing to database. Exception: System.Data.SqlClient.SqlException: Invalid object name ‘dbo.LogEntries’.

    1. Bill Moniz · · Reply

      I realise that your question is from a long time ago, but I just ran into the same problem, so I thought I’d post the solution here for future travellers…

      The problem is this commented-out line:

      <!– THIS is not required, read from the appsettings.json


      It actually IS required. We still need to give NLog the parameter, even though the value will only be provided in appsettings.json.

      If you un-comment line 15 of the nlog.config, it will work as described. 🙂

      1. Jonathan Casanueva Willumsen · ·

        Wow! this solved my problem 🙂

  2. Hi Ristogod

    If you set a breakpoint at the the target.ConnectionString, is the connection string correct in the debugger?

    Greetings Damien

  3. Ali Raza · · Reply

    Hi Can you tell me how to log for MySql database ? Hopefully you will reply soon.

  4. Valeriy · · Reply


    If you comment this line, then NLog silently crashes with error:

    “Error when writing to database. Exception: System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 – Could not open a connection to SQL Server) —> System.ComponentModel.Win32Exception”

    May be, this error was raised for application hosted on IIS… If you uncomment this line, then NLog works correctly.

    1. Hi Valeriy, Which line i have to comment in order to this to work?

      1. Valeriy · ·

        Hi Peter. Line 15 in nlog.config

  5. Kashif Ali · · Reply

    Not working after deployement to iis ,working in debug mode.

  6. […] Settings the NLog database connection string in the ASP.NET Core appsettings.json […]

  7. With NLog.Extension.Logging ver. 1.4.0 then you can now use `${configsetting}`

    See also:

Leave a Reply to .NET Core logging to MySQL using NLog - Cancel reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: