I've been studying python logging since a few days and I'm testing it today at work. I'm testing the following code:
import inspect
import logging
def customLogger(FileHandlerlogLevel, ConsoleHandlerLogLevel, file_path_and_name):
'''
- logLevel input values: DEBUG, INFO, WARNING, ERROR, CRITICAL
'''
# Gets the name of the class / method from where this method is called
loggerName = inspect.stack()[1][3]
logger = logging.getLogger(loggerName)
logger.setLevel(logging.DEBUG)
fileHandler = logging.FileHandler(file_path_and_name, mode="w")
fileHandler.setLevel(FileHandlerlogLevel)
formatter = logging.Formatter('%(name)s - %(lineno)d - %(asctime)s - %(levelname)s - %(message)s',
datefmt="%m/%d/%Y %I:%M:%S %p")
fileHandler.setFormatter(formatter)
logger.addHandler(fileHandler)
stream_handler = logging.StreamHandler()
stream_handler.setLevel(ConsoleHandlerLogLevel)
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)
return logger
test_logger = customLogger(logging.DEBUG, logging.DEBUG, "test_loggerv01.log")
test_logger.info("test 01")
So basically I have two handlers for a given logger. When I run the script the first time, this is what the console (Spyder) shows:
In [1]: runfile('C:/Users/aardem/Python_AA/AB/Corproates_Prj/custom_logger_andrea_v02.py', wdir='C:/Users/aardem/Python_AA/AB/Corproates_Prj')
<module> - 36 - 07/19/2018 06:32:22 PM - INFO - test 01
So far so good. Then, I change the info message to "test 02" (last line of my code), save and re-run the script. Now, the console shows the following:
In [2]: runfile('C:/Users/aardem/Python_AA/AB/Corproates_Prj/custom_logger_andrea_v02.py', wdir='C:/Users/aardem/Python_AA/AB/Corproates_Prj')
<module> - 36 - 07/19/2018 06:32:34 PM - INFO - test 02
<module> - 36 - 07/19/2018 06:32:34 PM - INFO - test 02
Again, if I change the last line of my script to:
test_logger.info("test 03")
then save and re-run the script, this is the new console output:
In [3]: runfile('C:/Users/aardem/Python_AA/AB/Corproates_Prj/custom_logger_andrea_v02.py', wdir='C:/Users/aardem/Python_AA/AB/Corproates_Prj')
<module> - 37 - 07/19/2018 06:38:20 PM - INFO - test 03
<module> - 37 - 07/19/2018 06:38:20 PM - INFO - test 03
<module> - 37 - 07/19/2018 06:38:20 PM - INFO - test 03
Can somebody help me with this unexpected problem? The same problem happens with the data saved inside the file "test_loggerv01.log". Thank you