简体   繁体   English

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

[英]Unable to set my connectionstring in NLog

The NLog.config file does not set the connection string. 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">

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

I put a breakpoint and the connection string is null; 我放了一个断点,连接字符串为null; 在此输入图像描述

My Startup method is as follows; 我的启动方法如下;

    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");
    }
}

EDIT - I change the logger rule to <logger name="*" minlevel="Trace" writeTo="db" /> but still it didn't output anything. 编辑 - 我将记录器规则更改为<logger name="*" minlevel="Trace" writeTo="db" />但仍然没有输出任何内容。 However I looked for the c:\\temp\\internal-nlog.txt and it had not been created. 但是我查找了c:\\ temp \\ internal-nlog.txt并且尚未创建它。 So it appears the nlog.config file is being ignored. 因此,似乎忽略了nlog.config文件。 But it is in my project next to the Startup.cs file. 但它位于Startup.cs文件旁边的项目中。

EDIT2: - the null configuration can be solved by setting "Copy to output directory" to "copy always". EDIT2: - 可以通过将“复制到输出目录”设置为“始终复制”来解决空配置。 From the comments underneath I have now got this working. 从下面的评论我现在有这个工作。

Updated answer 更新的答案

Since NLog.Web.AspNetCore 4.8 (NLog.Extensions.Logging 1.4 for .NET Core console programs) you could directly read from your appSettings.json 从NLog.Web.AspNetCore 4.8(适用于.NET Core控制台程序的NLog.Extensions.Logging 1.4)开始,您可以直接从appSettings.json中读取

${configsetting:name=MyConnectionString}

see docs 文档


Original answer 原始答案

Unfortunately reading connectionstrings/settings from appSettings.json / app.config is not yet supported in NLog for .NET core. 不幸的是,NLog for .NET核心尚不支持从appSettings.json / app.config读取连接字符串/设置。

Two options: 两种选择:

  1. Set the connectionstring programmatically, by using variables. 通过使用变量以编程方式设置连接字符串。 In your nlog.config: 在你的nlog.config中:

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

    and in code: (eg in Configure ) 并在代码中:(例如在Configure

     LogManager.Configuration.Variables["myConnectionstring"] = "...."; //read config here 
  2. Or, set the connectionstring in nlog.config. 或者,在nlog.config中设置connectionstring。

    In your nlog.config: 在你的nlog.config中:

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

    and using in your target in nlog.config: 并在nlog.config中使用目标:

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

Another option is to create and register a custom NLog layout-renderer (startup.cs): 另一种选择是创建和注册自定义NLog布局渲染器(startup.cs):

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

Which outputs the ConnectionString after having read it from your favorite configuration-location. 从您喜欢的配置位置读取后,它会输出ConnectionString。 Then you don't have the connectionstring in your nlog.config, but just refer to your custom layout-renderer. 然后你的nlog.config中没有connectionstring,只是引用你的自定义布局渲染器。

Maybe cheer for this pending issue: 也许为这个悬而未决的问题欢呼:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM