我需要动态更改 Serilog 的连接字符串。
在 StartUp.cs 中,我配置了 Serilog,如下所示:
public void ConfigureServices(IServiceCollection services)
{
var cm = new ConnectionManager(config);
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(config)
.Enrich.FromLogContext()
.WriteTo.MSSqlServer(
cm.GetConnectionString(cm.GetPropertyFromConfig("Serilog", "ConnectionName")),
sinkOptions: new MSSqlServerSinkOptions { TableName = cm.GetPropertyFromConfig("Serilog", "TableName"), SchemaName = cm.GetPropertyFromConfig("Serilog", "SchemaName") })
.CreateLogger();
services.AddLogging(s =>
{
s.ClearProviders();
s.AddSerilog(Log.Logger, dispose: true);
});
services.AddTransient(provider =>
{
var loggerFactory = provider.GetRequiredService<ILoggerFactory>();
const string categoryName = "Any";
return loggerFactory.CreateLogger(categoryName);
});
}
在 ChangeConnection.cs 中,我希望能够更改连接字符串
public ChangeConnection {
private readonly ILogger _logger;
public ChangeConnection(ILogger logger){
_logger = logger;
}
public void SwapConnection(string connectionString)
{
// Change the connection string for logger so all subsequent calls write to new database
}
}
在代码中的某个位置,进行调用以更改连接字符串。:
_logger.LogInformation("Logging to Current Database");
ChangeConnection.SwapConnection("new connection string");
_logger.LogInformation("Logging to New Database");
经过测试,这个需求恐怕无法实现。
我还在这里找到了已关闭的 github 问题:https://github.com/serilog-mssql/serilog-sinks-mssqlserver/issues/246
如果您仍然想要该功能,您可以提出新的 github 问题。