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 runinitialise_logger
. - I also tried "popping" all available handlers (following this seggestion) before running
initialise_logger
, but no handlers could be found, before runninginitialise_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)