如何在运行时更改NLog目标的连接字符串?

时间:2015-02-19 12:36:57

标签: c# logging asp.net-web-api nlog

在我的WebAPI应用程序中,我试图根据我的自定义标头值在Application_BeginRequest中登录几个单独的数据库。

为了实现这一点,我尝试修改target中的Nlog.config,如下所示:

<target name="database" 
        xsi:type="Database" 
        connectionString="${gdc:item=myConnectionstring}" 
        commandText="..sql command..">..params..</target>

并在Application_BeginRequest我尝试将myConnectionstring设置为:

GlobalDiagnosticsContext.Set("myConnectionString", connectionString);

但是这并没有奏效,并且出现了NLog的internalLogFile错误:

2015-02-19 12:12:48.8776 Error Error when writing to database System.InvalidOperationException: The ConnectionString property has not been initialized.
   at System.Data.SqlClient.SqlConnection.PermissionDemand()
   at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.Open()
   at NLog.Targets.DatabaseTarget.OpenConnection(String connectionString)
   at NLog.Targets.DatabaseTarget.WriteEventToDatabase(LogEventInfo logEvent)
   at NLog.Targets.DatabaseTarget.Write(LogEventInfo logEvent)

我尝试使用以下参数写入db(具有常量连接字符串配置):

<parameter name="@cn" layout="${gdc:myConnectionstring}"/>
<parameter name="@cn1" layout="${gdc:item=myConnectionstring}"/>

但它们似乎是空的,但是当我调试我的WebApi Action会抛出我希望写入数据库的错误时,GlobalDiagnosticsContext.Get("myConnectionString")会返回预期的值。

我做错了什么?为什么我可以在GlobalDiagnosticsContext.Get("myConnectionString")中看到预期值,但${gdc:item=myConnectionstring}会解析为空字符串?

2 个答案:

答案 0 :(得分:3)

找到另一种方法来实现这一目标:

var databaseTarget = (DatabaseTarget)LogManager.Configuration.FindTargetByName("database");
databaseTarget.ConnectionString = connectionString;
LogManager.ReconfigExistingLoggers();

但仍然不清楚为什么GlobalDiagnosticsContext内容不起作用..

答案 1 :(得分:2)

感谢您的解决方案!

但是,如果你想使用异步数据库目标,你需要首先获得包装目标:

DatabaseTarget databaseTarget;
var target = LogManager.Configuration.FindTargetByName("database");
if (target is AsyncTargetWrapper)
    databaseTarget = (target as AsyncTargetWrapper).WrappedTarget as DatabaseTarget;
else
    databaseTarget = target as DatabaseTarget;
if (databaseTarget == null)
    throw new NullReferenceException("Can't find DatabaseTarget with name 'database'");

databaseTarget.ConnectionString = connectionStringSelected.ConnectionString;
LogManager.ReconfigExistingLoggers();