我正在尝试使用 Serilog 登录我的 .NET 项目,但我注意到错误没有写入数据库。我打开 Serilog 的 SelfLog,这是显示的错误:
2022-11-01T15:58:26.9744639Z 由于以下错误,无法将 1 个日志事件写入数据库:已成功与服务器建立连接,但在登录过程中发生错误。 (提供程序:SSL 提供程序,错误:0 - 证书链由不受信任的机构颁发。)
这是我在 Program.cs 中对 Serilog 的设置:
var columnOptions = new ColumnOptions();
columnOptions.Store.Remove(StandardColumn.Properties);
columnOptions.Store.Remove(StandardColumn.MessageTemplate);
columnOptions.TimeStamp.NonClusteredIndex = true;
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(Config)
.Enrich.FromLogContext()
.Enrich.WithExceptionDetails()
.WriteTo.Console()
.WriteTo.MSSqlServer(
connectionString: Config.GetSection("DbConfiguration")["ConnString"],
sinkOptions: new MSSqlServerSinkOptions
{
TableName = Config.GetSection("Serilog")["TableName"],
SchemaName = "dbo",
AutoCreateSqlTable = false,
BatchPeriod = TimeSpan.FromMilliseconds(5)
},
columnOptions: columnOptions
)
.CreateLogger();
我已经确认我给 Serilog 的连接字符串与我通常用来访问数据库的连接字符串相同,并且我正在手动创建表,但是即使我将其设置为 true 并让 Serilog 自动创建它,它会抛出相同的无法登录的错误。我在网上的其他页面上找到了关于此错误的类似版本,但我找不到涉及 Serilog 的版本,并且其他页面与我正在做的事情无关。
有人可以帮助我了解发生了什么事吗?
最佳答案
从 Serilog.Sinks.MSSqlServer v5 开始,它使用 Microsoft.Data.SqlClient而不是 System.Data.SqlClient 来与 SQL Server 对话。 Starting with v4 of Microsoft.Data.SqlClient默认启用加密,并验证用于加密的证书的有效性。您有多种选择:
- 为您的 SQL Server 实例提供有效的证书 - 或让您的计算机信任该证书
- 使用旧版本的 Serilog.Sinks.MSSqlServer uses System.Data.SqlClient或使用old version of Microsoft.Data.SqlClient that doesn't enable encryption by default 。我只是在这里提到这一点,因为有人可能会建议它 - 不要采取这种方法!
- 调整连接字符串,使其忽略证书验证错误。这也不是一个好主意!
- 调整连接字符串以不使用加密 - 这不是一个好主意!
当您更新自己的代码以使用 Microsoft.Data.SqlClient 而不是 System.Data.SqlClient 时,您可能会遇到相同的问题。现在不妨硬着头皮使用您的机器信任的证书。
关于c# - Serilog 无法登录我的本地数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74294286/