开发者

Proper way to shutdown a logger instance in log4Net

开发者 https://www.devze.com 2023-03-03 03:55 出处:网络
I have a class to whose every instance i create a new logger and attache a buffer appender and a flie appender to it. Everything is being done runtime and no information is picked from the config file

I have a class to whose every instance i create a new logger and attache a buffer appender and a flie appender to it. Everything is being done runtime and no information is picked from the config file.

Now to release resources at the class's custom dispose method i need to shutdown that specific logger and release all of its attached resources so as to avoid any开发者_运维知识库 memory leak.

At the moment what i have been doing is atleast flush the file appender and write all logging information but that neither releases the lock on that specific logging file nor does it release any of its resources.

What is the proper way of shutting down the logger while not shutting down other active loggers that are in process

log4net.ILog log = log4net.LogManager.GetLogger(loggerName);

foreach (IAppender iapp in log.Logger.Repository.GetAppenders())
{
    BufferingAppenderSkeleton buffered = iapp as BufferingAppenderSkeleton;
    if (buffered is BufferingForwardingAppender)
    {
        ((BufferingForwardingAppender)buffered).Flush();
    }
}

log.Logger.Repository.Shutdown();

I hope i have made my question clear enough :)


This worked for me:

log.Logger.Repository.Shutdown();

or you can take the long route:

foreach (log4net.Appender.IAppender app in log.Logger.Repository.GetAppenders()) {
    app.Close();
}


In this instance, as you are not sharing any appenders, you should be able to use the IAppender.Close() method on all the appenders attached to your logger (this will also cause them all to be flushed).

You should cast the logger to IAppenderAttachable and get the appenders form there; this will allow you to make sure you only call Close() on the top level of your nested appenders. This should cause them to flush and close down their own children in the correct order.

http://logging.apache.org/log4net/release/sdk/html/M_log4net_Appender_IAppender_Close.htm

This will be very dangerous if you are using a standard log4net setup with a configuration!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号