18

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 :)

Basit Anwer
  • 6,742
  • 7
  • 45
  • 88

2 Answers2

24

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();
}
JJ_Coder4Hire
  • 4,706
  • 1
  • 37
  • 25
  • 3
    From the [docs](http://logging.apache.org/log4net/log4net-1.2.13/release/sdk/log4net.Repository.ILoggerRepository.Shutdown.html): `Remarks: Shutting down a repository will safely close and remove all appenders in all loggers including the root logger. Some appenders need to be closed before the application exists. Otherwise, pending logging events might be lost. The Shutdown method is careful to close nested appenders before closing regular appenders. This is allows configurations where a regular appender is attached to a logger and again to a nested appender.` – brichins Jun 15 '17 at 19:12
  • 2
    Curious if there is a way to start it back up? What I'm looking at is Shutdown, Save/Send log files, Startup. – kenny Mar 21 '19 at 14:01
3

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!

jedigo
  • 901
  • 8
  • 12