sql-server – NLog,ASP.NET Core和SQL – 找不到服务器或无法访问服务器

我一直在努力让一个ASP.NET Core站点与NLog一起工作.它工作正常,直到我尝试写入SQL数据库.我已经尝试过本地数据库和Azure数据库 – 所有这些都有同样的问题.我甚至已将nlog表添加到已知数据库,该站点已连接到(使用EF).

我正在使用nuget包:NLog.Web.AspNetCore

无论如何,我得到以下内容:

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.

以下是我配置的方法(我尝试更改这些语句的顺序):

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

这是我的nlog配置:

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

最后,这是我的appsettings.json:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\projectsV13;Database=XXXX;Trusted_Connection=True;MultipleActiveResultSets=true",
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

最佳答案 您没有在数据库目标中使用变量“connectionString”.

你还需要

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

NLog中的变量不会自动绑定到目标.您需要在配置中设置和使用它们.

更新

从NLog.Web.AspNetCore 4.8(适用于.NET Core控制台程序的NLog.Extensions.Logging 1.4)开始,您可以直接从appSettings.json中读取

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

docs

点赞