使用AdoNetAppender刷新Log4Net缓冲区

时间:2015-05-27 18:36:56

标签: c# asp.net log4net

我正在使用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小时执行代码块的线程并刷新缓冲区。

1 个答案:

答案 0 :(得分:5)

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();
    }
}