Search code examples
pythonlogginglevelslog-level

Configure Logging level in Python for each file individually


I'm using

logging.basicConfig(format=log_format, level=logging.DEBUG)

in my main script. I like seeing DEBUG messages in most cases. But I want to hide all DEBUG messages from a certain script - lets say connectionpool.py. How can i set connectionpool.py's Log level to INFO while having the rest at DEBUG?


Solution

  • By default, you don't set them by file, but by logging handler name.

    Assuming it's urllib3.connectionpool that's bothering you (it's generally pretty noisy on DEBUG),

    logging.getLogger('urllib3.connectionpool').setLevel(logging.INFO)
    

    If it really is disabling a file you're after, you could also set up a custom logging filter on your logger to swallow those log records altogether before they're output.

    Assuming you haven't set up a more complex hierarchy to split logging output,

    logging.getRoot().addFilter(lambda rec: 'connectionpool.py' not in rec.pathname)
    

    would disallow all messages emitted from a module with connectionpool.py in the name.