Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nlog Target Database set connection information at runtime

Tags:

c#

nlog

Using Nlog and a Database target, is there a way to set the connection information at runtime?

like image 945
Gratzy Avatar asked Jan 16 '23 20:01

Gratzy


1 Answers

I remember some colleague of mine doing something similar. He found this answer: http://nlog-forum.1685105.n2.nabble.com/DDL-for-Database-Table-How-to-set-Connection-String-Programmatically-td5241103.html that was working perfectly fine.

From the link above

The easiest way of overriding connection string is through the use of GDC:

<target name="db" type="Database" connectionString="${gdc:myConnectionstring}" ... />

Now in your code you can simply do:

GDC.Set("myConnectionString", "Server=.;database=.....");

You can also modify the target:

var config = LogManager.Configuration;
var dbTarget = (DatabaseTarget)config.FindTargetByName("db");
dbTarget.ConnectionString = "server=.;...";
LogManager.ReconfigExistingLoggers();
like image 108
Maciek Talaska Avatar answered Jan 23 '23 05:01

Maciek Talaska