gpt4 book ai didi

c# - log4net - 如何在连接断开后重新建立与数据库的连接

转载 作者:行者123 更新时间:2023-11-30 12:39:36 25 4
gpt4 key购买 nike

我在我的 WebAPI 应用程序中使用 log4net 的 AdoNetAppender。每隔几周,记录器就会突然停止记录,只有在我重新启动 Web 服务后,它才会再次开始记录。我已经向 appender 添加了一个实现 IErrorHandler 的自定义 ErrorHandler,以便捕获任何异常,如下所示:

public class MyErrorHandler : IErrorHandler
{
private AdoNetAppender ParentAppender { get; set; }
public MyErrorHandler(AdoNetAppender parentAppender)
{
ParentAppender = parentAppender;
}
public void Error(string message)
{
Debug.WriteLine(message);
}

public void Error(string message, Exception ex)
{
Debug.WriteLine(message + " ,Exception:" + ex.ToString());
}

public void Error(string message, Exception ex, ErrorCode errorCode)
{

}
}

,这些是我收到的消息和异常:

Exception while writing to database

System.InvalidOperationException: The requested operation cannot be completed because the connection has been broken.
at System.Data.SqlClient.SqlInternalConnectionTds.ExecuteTransaction(TransactionRequest transactionRequest, String name, IsolationLevel iso, SqlInternalTransaction internalTransaction, Boolean isDelegateControlRequest)
at System.Data.SqlClient.SqlInternalConnection.BeginSqlTransaction(IsolationLevel iso, String transactionName, Boolean shouldReconnect)
at System.Data.SqlClient.SqlConnection.BeginTransaction(IsolationLevel iso, String transactionName)
at System.Data.SqlClient.SqlConnection.BeginDbTransaction(IsolationLevel isolationLevel)
at System.Data.Common.DbConnection.System.Data.IDbConnection.BeginTransaction()
at log4net.Appender.AdoNetAppender.SendBuffer(LoggingEvent[] events)

我已经在 appender 中将 ReconnectOnError 属性设置为 true,但它不会重新连接。如何让 appender 重新建立与数据库的连接,或者如何重新初始化 appender?顺便说一句,我将 appender 传递给 ErrorHandler,所以当我捕获到异常时我可以访问它。

最佳答案

我按照 tattarrattat 的建议,通过将 ConnectRetryCount=0 添加到我的连接字符串中解决了这个问题和 https://stackoverflow.com/a/38333737/5850144 .根据MSDN , ConnectRetryCount 是

The number of reconnections attempted after identifying that there was an idle connection failure.

Set to 0 to disable reconnecting on idle connection failures

所以我的猜测是,通过将其设置为 0,SqlClient 不会尝试重新连接,而是 log4net 本身会尝试重新连接(因为我将 ReconnectOnError 属性设置为 true)。

关于c# - log4net - 如何在连接断开后重新建立与数据库的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44783604/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com