I have an NLog database target that looks like this:
<target xsi:type="Database" name="database"
connectionString="Server=.\SQLEXPRESS;Database=ApplicationOne;Trusted_Connection=True;MultipleActiveResultSets=true;User Id=User0101;Password=PW0101"
commandText="INSERT INTO [SchemaOne].[EventLogs](Id, Message, Level, Logger )VALUES(NewID(), @Message, @Level, @Logger)">
<parameter name="@Message" layout="${message}" />
<parameter name="@Level" layout="${level}" />
<parameter name="@Logger" layout="${logger}" />
</target>
Is it possible to change the connectionString to use connectionStringName from my appsettings instead?
My appsettings is called dssettings.json and it contains the connection details here:
"DatabaseConfiguration": {
"DatabaseName": "ApplicationOne",
"ConnectionName": "DefaultConnection",
"ConnectionString": "Server=.\\SQLEXPRESS;Database=ApplicationOne;Trusted_Connection=True;MultipleActiveResultSets=true;User Id=User0101;Password=PW0101"
},
In ASP.NET Core the configuration system is very flexible, and the connection string could be stored in appsettings. json , an environment variable, the user secret store, or another configuration source. See the Configuration section of the ASP.NET Core documentation for more details.
json file, right click on the Project in Solution Explorer. Then click Add, then New Item and then choose App Settings File option (shown below) and click Add button. Once the File is created, it will have a DefaultConnection, below that a new Connection String entry is added.
Update NLog.Extension.Logging ver. 1.4.0
With NLog.Extension.Logging ver. 1.4.0 then you can now use ${configsetting}
See also: https://github.com/NLog/NLog/wiki/ConfigSetting-Layout-Renderer
Original Answer
With help from nuget-package NLog.Appsettings.Standard then you can normally do this:
<extensions>
<add assembly="NLog.Appsettings.Standard" />
</extensions>
<targets>
<target xsi:type="Database" name="database"
connectionString="${appsettings:name=DatabaseConfiguration.ConnectionString}"
commandText="INSERT INTO [SchemaOne].[EventLogs](Id, Message, Level, Logger )VALUES(NewID(), @Message, @Level, @Logger)">
<parameter name="@Message" layout="${message}" />
<parameter name="@Level" layout="${level}" />
<parameter name="@Logger" layout="${logger}" />
</target>
</targets>
But because you are using a special dssettings.json
(instead of appsettings.json), then you probably have to implement your own custom NLog layout renderer:
https://github.com/NLog/NLog/wiki/How-to-write-a-custom-layout-renderer
Maybe you can use the source-code from the above nuget-package as inspiration for loading dssettings.json
. Or maybe create PullRequest that adds support for specifying non-default config-filename.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With