使用AdoNetAppender刷新Log4Net缓冲区
本文关键字:缓冲区 Log4Net 刷新 AdoNetAppender 使用 | 更新日期: 2023-09-27 17:50:52
我使用Log4Net与AdoNetAppender,我喜欢在特定的时间或时间段刷新缓冲区。
可能是我没有错,Log4Net不提供此功能,为此我必须创建自己的Appender,但我不知道或可能是我困惑如何实现这一点。
有谁能帮我一下吗?对于flush,我应该使用以下代码,但它没有时间或超时功能。
public void FlushBuffers()
{
ILoggerRepository rep = LogManager.GetRepository();
foreach (IAppender appender in rep.GetAppenders())
{
var buffered = appender as BufferingAppenderSkeleton;
if (buffered != null)
{
buffered.Flush();
}
}
}
编辑
Log4Net是在Asp中实现的。Net网站,我需要冲洗这个扔网站。
也许我可以创建线程,执行代码块在每2小时和刷新缓冲区。
public class FlushingAdoNetAppender : AdoNetAppender
{
private Timer flushTimer;
private TimeSpan flushInterval = TimeSpan.FromMinutes(5);
public FlushingAdoNetAppender()
{
// Enable for debugging purposes
// LogLog.InternalDebugging = true;
}
public TimeSpan FlushInterval
{
/*
The interval after which the buffer will be flushed. Defaults to 5 minutes
Example config:
<appender name="DatabaseAppender" type="Your.Namespace.FlushingAdoNetAppender">
<flushInterval value="00:30:00" />
</appender>
*/
get { return flushInterval; }
set { flushInterval = value; }
}
public override void ActivateOptions()
{
flushTimer = new Timer(flushInterval.TotalMilliseconds);
LogLog.Debug(GetType(), "Flush timer interval is " + TimeSpan.FromMilliseconds(flushTimer.Interval));
flushTimer.Enabled = true;
flushTimer.Elapsed += FlushLog;
flushTimer.Start();
base.ActivateOptions();
}
protected override void OnClose()
{
// This is called by log4net when reloading the config
flushTimer.Stop();
flushTimer.Dispose();
base.OnClose(); // calls Flush()
}
private void FlushLog(object sender, ElapsedEventArgs e)
{
LogLog.Debug(GetType(), "Flushing logs");
Flush();
}
}