Unable to set connection string in NLog

The NLog.config file does not establish a connection string.

<?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 set a breakpoint and the connection string is empty; enter image description here

My launch 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 doesn’t do anything <logger name="*" minlevel="Trace" writeTo="db"/> . However, I searched c: \ temp \ internal-nlog.txt and it was not created. It looks like the nlog.config file is being ignored. But this is in my project next to the Startup.cs file.

EDIT2: - zero configuration can be solved by setting "Copy to output directory" to "always copy". From the comments below I now got it working.

+9
c # asp.net-core nlog
source share
2 answers

Updated Answer

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

 ${configsetting:name=MyConnectionString} 

see documents


Original answer

Unfortunately, reading lines / connection settings from appSettings.json / app.config is not yet supported in NLog for the .NET kernel.

Two options:

  1. Set the connection string programmatically using variables. In your nlog.config:

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

    and in code: (e.g. in Configure )

     LogManager.Configuration.Variables["myConnectionstring"] = "...."; //read config here 
  2. Or set the connection string in nlog.config.

    In your nlog.config:

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

    and use for your purpose in nlog.config:

     <target ... connectionString="${var:myConnectionstring}" ... /> 
+8
source share

Another option is to create and register your own NLog layout rendering (startup.cs):

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

What the ConnectionString displays after reading from your favorite configuration location. Then you don't have a connection string in your nlog.config, but just refer to your custom layout rendering.

Perhaps I welcome this unresolved issue:

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

+2
source share

All Articles