我在我的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和https://*.com/a/38333737/5850144建议的连接字符串中添加ConnectRetryCount = 0来解决这个问题.根据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).