I am getting duplicate output for Python logging with custom logger. Below is the section of logging code and output. For some reason if I remove the logger.setLevel(logging.DEBUG) line, the logger doesn't seem to respect the console_handler.setLevel(logging.DEBUG) line, and there is no output at all.
Code
...
args = parser.parse_args()
if args.log:
# Create custom logger
logger = logging.getLogger('a')
logger.setLevel(logging.DEBUG)
# Create handler
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG)
# Create formatter and add it to handler
console_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
console_handler.setFormatter(console_formatter)
# Add handler to logger
logger.addHandler(console_handler)
try:
...
except IndexError as ie:
logger.info(f'Test')
...
except Exception as ex:
logger.error(f'Exception: {ex}')
Output
2022-07-11 11:29:59,409 - INFO - Test
INFO:a:Test
importing) is callinglogging.basicConfig. By default, that function uses a formatter that gives logs likeINFO:a:Test.