Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Logging Duplicate Output

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

2022-07-11 11:29:59,409 - INFO - Test
INFO:a:Test

>Solution :

As far as I remember the setting propagates to higher level (ancestor) loggers. You can read about it here.

I would suggest adding logger.propagate = False after initializing logger a:

logger = logging.getLogger('a')
logger.propagate = False
logger.setLevel(logging.DEBUG)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading