我在我的asp.net应用程序中使用AdoNetAppender (SQL server),如果出现与SQL的连接问题,我想使用RollingFileAppender。有没有一种方法可以配置只有在AdoNetAppender出现问题时才使用RollingFileAppender?
谢谢。
谢谢。
log4net中没有针对此类故障转移场景的内置支持,问题在于在log4net架构中,附加器相互之间相当独立。
然而,常见的设置是使两个附加器并行记录,只不过文件附加器仅保留一周的数据。如果AdoNetAppender失败,您将始终拥有文件中最新的数据。
但我明确看到这里需要一个附加器,它可以具有子附加器的优先级列表,在发生故障时进行一些简单的故障转移。这应该不太难实现,可以建立在AppenderSkeleton的基础上。
public class FailoverAppender : AppenderSkeleton
{
private AppenderSkeleton _primaryAppender;
private AppenderSkeleton _failOverAppender;
....
}
protected override void Append(LoggingEvent loggingEvent)
{
if (LogToFailOverAppender)
{
_failOverAppender?.DoAppend(loggingEvent);
}
else
{
try
{
_primaryAppender?.DoAppend(loggingEvent);
}
catch
{
ActivateFailOverMode();
Append(loggingEvent);
}
}
}
class FailOverErrorHandler : IErrorHandler
{
public FailOverAppender FailOverAppender { get; set; }
public FailOverErrorHandler(FailOverAppender failOverAppender)
{
FailOverAppender = failOverAppender;
}
public void Error(string message, Exception e, ErrorCode errorCode)
=> FailOverAppender.ActivateFailOverMode();
public void Error(string message, Exception e)
=> FailOverAppender.ActivateFailOverMode();
public void Error(string message)
=> FailOverAppender.ActivateFailOverMode();
}
<!--This custom appender handles failovers. If the first appender fails, it'll delegate the message to the back appender-->
<appender name="FailoverAppender" type="MoreAppenders.FailoverAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/>
</layout>
<!--This is a custom test appender that will always throw an exception -->
<!--The first and the default appender that will be used.-->
<PrimaryAppender type="MoreAppenders.ExceptionThrowerAppender" >
<ThrowExceptionForCount value="1" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/>
</layout>
</PrimaryAppender>
<!--This appender will be used only if the PrimaryAppender has failed-->
<FailOverAppender type="log4net.Appender.RollingFileAppender">
<file value="log.txt"/>
<rollingStyle value="Size"/>
<maxSizeRollBackups value="10"/>
<maximumFileSize value="100mb"/>
<appendToFile value="true"/>
<staticLogFileName value="true"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/>
</layout>
</FailOverAppender>
</appender>