Is there a way to programmably flush the buffer in log4net

你。 提交于 2019-11-28 17:23:31

Assuming you're using log4net out of the box, you can dig your way down & flush the appender like this:

public void FlushBuffers()
{
    ILog log = LogManager.GetLogger("whatever");
    var logger = log.Logger as Logger;
    if (logger != null)
    {
        foreach (IAppender appender in logger.Appenders)
        {
            var buffered = appender as BufferingAppenderSkeleton;
            if (buffered != null)
            {
                buffered.Flush();
            }
        }
    }
}

Edit: I wrote the above under the assumption that you wanted to flush the appenders for a specific ILog (probably a bad assumption now that I re-read the question), but as Stefan points out in a comment below, you can simplify the code a little if you want to flush all appenders across the whole repository as follows:

public void FlushBuffers()
{
    ILoggerRepository rep = LogManager.GetRepository();
    foreach (IAppender appender in rep.GetAppenders())
    {
        var buffered = appender as BufferingAppenderSkeleton;
        if (buffered != null)
        {
            buffered.Flush();
        }
    }
}

Today simpler option is available:

LogManager.Flush();

Flushes logging events buffered in all configured appenders in the default repository. https://logging.apache.org/log4net/release/sdk/html/M_log4net_LogManager_Flush.htm

It is highly recommended to add a timeout, like

LogManager.Flush(3000);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!