Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to shutdown a logger instance in log4Net

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

like image 987
Basit Anwer Avatar asked May 05 '11 05:05

Basit Anwer


People also ask

What are the main components of log4net briefly describe how loggers work in log4net?

Log4net has three main components: loggers, appenders and layouts. These three types of components work together to enable developers to log messages according to message type and level, and to control at runtime how these messages are formatted and where they are reported.

Is log4net a Threadsafe?

Is log4net thread-safe? Yes, log4net is thread-safe.


2 Answers

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();
}
like image 167
JJ_Coder4Hire Avatar answered Sep 20 '22 15:09

JJ_Coder4Hire


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!

like image 39
jedigo Avatar answered Sep 16 '22 15:09

jedigo