Issue
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)
Solution
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.
Answered By - PeterLustig20
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.