NLog, ASP.NET Core, and SQL Server Not Found or Unavailable

I am trying to get an ASP.NET Core site working with NLog. It works fine until I try to write an SQL database. I tried local and Azure databases - all with the same problem. I even added the nlog table to a well-known database that the site is already connected to (with EF).

I am using the nuget package: NLog.Web.AspNetCore

Regardless, I get the following:

Error 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 available. Verify that the instance name is correct and that SQL Server is configured to allow remote connections.

This is how I set things up (I 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 configuration:

<?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>

Finally, 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"
    }
  }
}
+4
source share
2 answers

You are not using the "connectionString" variable for your database target.

You also need

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

Variables in NLog are not automatically bound to the target. You must install and use them in your config.

Refresh

Starting with NLog.Web.AspNetCore 4.8 (NLog.Extensions.Logging 1.4 for .NET Core Console Programs), you can directly read from your appSettings.json

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

see documents

+2
source

Primarily,

ConnectionString looks different

Local, . .

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

-: . , connectionString.

-1

Source: https://habr.com/ru/post/1675524/


All Articles