2

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
1
  • 2
    My guess is that some code somewhere (possibly from a module that you are importing) is calling logging.basicConfig. By default, that function uses a formatter that gives logs like INFO:a:Test. Commented Jul 11, 2022 at 18:41

1 Answer 1

7

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)
Sign up to request clarification or add additional context in comments.

2 Comments

thank you for the help! apparently it is the propagate property, which kind of makes me wonder why would this be a default behavior to auto propagate to ancestor loggers.
Important subtlety: setting logger.propagate = False inside a separate function where the logger is created (containing the logging.getLogger() call) does not work. But setting logger.propagate = False after invoking such a create_logger() function does work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.