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.
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.
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.initialise_logger, but no handlers could be found, before running initialise_logger.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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With