Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset python Logger to prevent duplicate logging records

Context

In a module with several classes and methods I use the python logging class with a global variable, called logger. It is initialised by the method initialise_logger (see below) once the module is called.

Problem

When I execute the module multiple times from Spyder, the logger creates multiple logging records for every logger message, i.e. after the first run the message "xyz" is printed one time, after the second run it is printed two times etc. When I close Spyder and open it again, the first run of the module starts with one printed message again.

What I tried

  • I tried to skip the initialisation of the logger (initialise_logger) by checking, if a logger with the same name already already exists (following this post). This failed since the logger with the specified name does indeed not exist before I run initialise_logger.
  • I also tried "popping" all available handlers (following this seggestion) before running initialise_logger, but no handlers could be found, before running initialise_logger.

My Code

def initialise_logger():
    
    global logger
    
    logger = logging.getLogger("reader")
    logger.setLevel(logging.DEBUG)
    
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.DEBUG)
    
    file_handler = logging.FileHandler("mylogfile.log")
    file_handler.setLevel(logging.DEBUG)
    
    logger.addHandler(console_handler)
    logger.addHandler(file_handler)
like image 769
PeterLustig20 Avatar asked May 19 '26 18:05

PeterLustig20


1 Answers

Solved it:

I created a new method destroy_logger which is triggered at the end of the entire process. It closes and deletes all handlers. This is what's inside of the method:

def destroy_logger():
    
    global logger
    
    while logger.hasHandlers():
        logger.handlers[0].close
        logger.removeHandler(logger.handlers[0])

This question here helped me solving it. It also mentions a problem I noticed as well: The log file cannot be deleted as long as the IDE is opened. This problem is also solved by my method above.

like image 117
PeterLustig20 Avatar answered May 22 '26 10:05

PeterLustig20



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!