无法为NLog设置我的连接字符串

编辑 - 重新开始。 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:tempinternal-nlog.txt">

  <!-- Load the ASP.NET Core plugin -->
  <extensions>
    <add assembly="NLog.Web.AspNetCore" />
  </extensions>
  <variable name="SirNLogDb" value="data source=SQL_MULALLEY;initial catalog=LogFiles;User ID=xxx;Password=yyy;">
  </variable>
  <!--  providerName="System.Data.SqlClient"-->

  <!-- the targets to write to -->
  <targets>
    <target name="db"
            xsi:type="Database"
            dbProvider="System.Data.SqlClient"
            connectionString="${var:SirNLogDb}"
            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 to map from logger name to target -->
  <rules>
    <!--All logs, including from Microsoft-->
    <logger name="*" minlevel="Trace" writeTo="database" />
  </rules>
</nlog>

我把一个断点和连接字符串为空; 在这里输入图像描述

我的启动方法如下;

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvcCore()
            .AddMvcOptions(o => o.OutputFormatters.Add(
                new JsonOutputFormatter(new JsonSerializerSettings(), ArrayPool<char>.Shared)));
        var connectionStringMSurveyV2 = Configuration.GetConnectionString("MSurveyV2Db");
        services.AddScoped<MSurveyV2Db>(_ => new MSurveyV2Db(connectionStringMSurveyV2));
        var connectionStringSir = Configuration.GetConnectionString("SirDb");
        services.AddScoped<SirDb>(_ => new SirDb(connectionStringSir));
        services.AddScoped<IPropertiesRepo, PropertiesRepo>();
        services.AddScoped<ISirUoW, SirUoW>();
        services.AddScoped<Services.IMailService, Services.MailService>();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole();
        loggerFactory.AddDebug();
        loggerFactory.AddNLog();
        //add NLog.Web
        app.AddNLogWeb();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler();
        }

        app.UseMvc();
        AutoMapper.Mapper.Initialize(cfg =>
        {
            cfg.CreateMap<Exception, OperationStatus>();
            cfg.CreateMap<ViewSelectedContracts, ContractDto>();
        });
        var logger = LogManager.GetCurrentClassLogger();
        logger.Info("Logged in");
    }
}

编辑 - 我将记录器规则更改为<logger name="*" minlevel="Trace" writeTo="db" />但仍然没有输出任何内容。 但是,我查找了c: temp internal-nlog.txt,但它尚未创建。 所以看起来nlog.config文件被忽略。 但它在我的项目旁边的Startup.cs文件。

编辑2: - 空配置可以通过将“复制到输出目录”设置为“始终复制”来解决。 从下面的评论我现在得到了这个工作。


不幸的是,在NLog for .NET核心中尚不支持从appSettings.json / app.config读取连接字符串/设置。

两种选择:

  • 通过使用变量以编程方式设置连接字符串。 在你的nlog.config中:

    <target ... connectionString="${var:myConnectionstring}"  ... />
    

    并在代码中:(例如在Configure

    LogManager.Configuration.Variables["myConnectionstring"] = "...."; //read config here
    
  • 或者,在nlog.config中设置连接字符串。

    在你的nlog.config中:

    <variable name="myConnectionstring" value="...." />  
    

    并在你的目标中使用nlog.config:

    <target ... connectionString="${var:myConnectionstring}" ... />
    

  • 另一种选择是创建并注册一个自定义的NLog布局渲染器(startup.cs):

    https://github.com/NLog/NLog/wiki/How-to-write-a-custom-layout-renderer

    在从您最喜欢的配置位置读取ConnectionString后输出ConnectionString。 然后,在nlog.config中没有连接字符串,但只需引用您的自定义布局渲染器。

    也许为这个悬而未决的问题欢呼:

    https://github.com/NLog/NLog.Web/issues/107

    链接地址: http://www.djcxy.com/p/96215.html

    上一篇: Cannot set my connection string for NLog

    下一篇: CSS v Photoshop Box Shadows: Lost in Translation