I have a .net core 3.1 Console project. I'm trying to set it up to use NLog. I use 2 targets, db and file. I can write to the file but can't to the db. I'm sure the connection string is correct because I use it in other projects but they were written in 4.7 framework.
This is my app.config setting:
<connectionStrings>
<add name="NLog" connectionString="Data Source=mySource;Initial Catalog=MyLogging;Integrated Security=SSPI;" />
</connectionStrings>
and this is my attempt to set it up in the target:
<?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="Info"
internalLogFile="c:\temp\nlog-internal.log">
<!-- enable asp.net core layout renderers -->
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<!-- the targets to write to -->
<targets>
<target name="database" xsi:type="Database" connectionString="${configsetting:name=NLog}" commandType="StoredProcedure" commandText="[dbo].[MyLogEntry]">
</target>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="Database" />
</rules>
</nlog>
and the error message from the c:\temp\nlog-internal.log is:
2021-02-10 16:11:48.3381 Error DatabaseTarget(Name=database): Error when writing to database. Exception: System.InvalidOperationException: The ConnectionString property has not been initialized.
at System.Data.SqlClient.SqlConnection.PermissionDemand()
at System.Data.SqlClient.SqlConnectionFactory.PermissionDemand(DbConnection outerConnection)
at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.Open()
at NLog.Targets.DatabaseTarget.OpenConnection(String connectionString, LogEventInfo logEventInfo)
at NLog.Targets.DatabaseTarget.EnsureConnectionOpen(String connectionString, LogEventInfo logEventInfo)
at NLog.Targets.DatabaseTarget.WriteLogEventToDatabase(LogEventInfo logEvent, String connectionString)
is the problem at the: connectionString="${configsetting:name=NLog}"
The app.config isn't really suitable in ASP.NET Core. It's possible, but it's dirty.
It's recommend to move to JSON application settings, like appsettings.json (see Configuration in ASP.NET Core)
For example:
appsettings.json:
and usages:
${configsetting:item=ConnectionStrings.NLog}
Please note, for
${configsetting}
you need one of these packages:See https://nlog-project.org/config/?tab=layout-renderers&search=configsetting