NLog, ASP.NET Core and SQL - The server was not found or was not accessible

4

I've been trying to get an ASP.NET Core site working with NLog. It works fine until I try to write to a SQL Database. I've tried local databases and Azure databases - all with the same problem. I've even added the nlog table to a known database, one the site already connects to (with EF).

I'm using the nuget package: NLog.Web.AspNetCore

No matter what, I get the following:

Error Error when writing to database. Exception: System.Data.SqlClient.SqlException (0x80131904): 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.

Here is how I am configuring things (I have tried changing the order of these statements):

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
            loggerFactory.AddNLog();
            app.AddNLogWeb();
            env.ConfigureNLog("nlog.config");
            LogManager.Configuration.Variables["connectionString"] = Configuration.GetConnectionString("DefaultConnection");
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
//etc...

Here is my nlog config:

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      internalLogLevel="Warn"
      internalLogFile="c:\temp\internal-nlog.txt">

  <!-- define various log targets -->
  <targets>
    <target name="db"
            xsi:type="Database"
            commandType="StoredProcedure"
            commandText="[dbo].[NLog_AddEntry_p]">
      <parameter name="@machineName"    layout="${machinename}" />
      <parameter name="@siteName"       layout="${iis-site-name}" />
      <parameter name="@logged"         layout="${date}" />
      <parameter name="@level"          layout="${level}" />
      <parameter name="@username"       layout="${aspnet-user-identity}" />
      <parameter name="@message"        layout="${message}" />
      <parameter name="@logger"         layout="${logger}" />
      <parameter name="@properties"     layout="${all-event-properties:separator=|}" />
      <parameter name="@serverName"     layout="${aspnet-request:serverVariable=SERVER_NAME}" />
      <parameter name="@port"           layout="${aspnet-request:serverVariable=SERVER_PORT}" />
      <parameter name="@url"            layout="${aspnet-request:serverVariable=HTTP_URL}" />
      <parameter name="@https"          layout="${when:inner=1:when='${aspnet-request:serverVariable=HTTPS}' == 'on'}${when:inner=0:when='${aspnet-request:serverVariable=HTTPS}' != 'on'}" />
      <parameter name="@serverAddress"  layout="${aspnet-request:serverVariable=LOCAL_ADDR}" />
      <parameter name="@remoteAddress"  layout="${aspnet-request:serverVariable=REMOTE_ADDR}:${aspnet-request:serverVariable=REMOTE_PORT}" />
      <parameter name="@callSite"       layout="${callsite}" />
      <parameter name="@exception"      layout="${exception:tostring}" />
    </target>
  </targets>

  <rules>
    <logger name="*" minlevel="Trace" writeTo="db" />
  </rules>
</nlog>

Last, here is my appsettings.json:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\projectsV13;Database=XXXX;Trusted_Connection=True;MultipleActiveResultSets=true",
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}
sql-server
asp.net-core
nlog
asked on Stack Overflow Apr 24, 2017 by Schwammy • edited Apr 24, 2017 by Julian

2 Answers

2

You aren't using the variable "connectionString" in your db target.

You also need

<target name="db"
   .. 
   connectionString="${var:connectionString}"
>

Variables in NLog are not automatically bound to a target. You need to set and use them in your config.

update

Since NLog.Web.AspNetCore 4.8 (NLog.Extensions.Logging 1.4 for .NET Core console programs) you could directly read from your appSettings.json

<target name="db"
   .. 
   connectionString="${configsetting:name=ConnectionStrings.DefaultConnection}"
>

see docs

answered on Stack Overflow Apr 24, 2017 by Julian • edited Feb 5, 2019 by Rolf Kristensen
-1

First of all,

ConnectionString is look like different

if you are using Local, you can take this error. But if you have a server define code is like this.

"ConnectionStrings": {  "DatabaseContext": "Server=(localdb)\\mssqllocaldb;Database=NAME;Trusted_Connection=True;MultipleActiveResultSets=true"}

In my opinion: The second reason about error. Maybe you can not read correctly to connectionString.

answered on Stack Overflow Apr 24, 2017 by aemre • edited Dec 29, 2017 by aemre

User contributions licensed under CC BY-SA 3.0