[Python] Prevent loggers of dependency packages from logging [duplicate]

Discussão em 'Python' iniciado por Stack, Setembro 2, 2025.

  1. Stack

    Stack Membro Participativo

    Consider the following example:

    import logging
    import requests
    logging.basicConfig(
    level=logging.DEBUG,
    force=True,
    format="{asctime} - {name} - {levelname} - {message}",
    style="{",
    datefmt="%Y-%m-%d %H:%M:%S"
    )
    requests.get("https://www.google.com")
    logging.debug("Page retrieved")


    This results in:

    2025-09-02 18:00:58 - urllib3.connectionpool - DEBUG - Starting new HTTPS connection (1): www.google.com:443
    2025-09-02 18:00:58 - urllib3.connectionpool - DEBUG - https://www.google.com:443 "GET / HTTP/1.1" 200 None
    2025-09-02 18:00:58 - root - DEBUG - Page retrieved


    But I only want to see the debug logs of my application, not of the dependencies.

    It's find that the dependencies logs at the warning or error or critical level, but not at the info or debug level.

    What is the most pythonic way to disable logging at the info and debug level from the dependencies?

    I tried something like:

    # Loop over non-root loggers
    non_root_loggers = list(logging.root.manager.loggerDict.keys())
    for logger in non_root_loggers:
    nrlogger = logging.getLogger(logger)
    nrlogger.setLevel(logging.WARNING)
    for handl in nrlogger.handlers:
    nrlogger.removeHandler(handl)
    nrlogger.propagate = True


    to be put before logging.basicConfig, but doesn't seem very pythonic

    Continue reading...

Compartilhe esta Página